<?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 Vitalismutwiri on Medium]]></title>
        <description><![CDATA[Stories by Vitalismutwiri on Medium]]></description>
        <link>https://medium.com/@vitalismutwiri?source=rss-266ae7508a8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5GAimdjtCXYrZfN2</url>
            <title>Stories by Vitalismutwiri on Medium</title>
            <link>https://medium.com/@vitalismutwiri?source=rss-266ae7508a8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:59:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vitalismutwiri/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[35,872 New Vulnerabilities in Just 6 Months. Is Your Application Secure?]]></title>
            <link>https://medium.com/@vitalismutwiri/35-872-new-vulnerabilities-in-just-6-months-is-your-application-secure-3990e6dfa1fa?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3990e6dfa1fa</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cloud-security]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:20:35 GMT</pubDate>
            <atom:updated>2026-10-24T04:20:35.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*65ZtAseK8LSRl1Pk" /></figure><p>It’s 2026. We’re talking about Artificial General Intelligence (AGI), AI agents are writing entire applications, and we’re shipping code faster than ever. Yet here we are, still battling security vulnerabilities. Are we building smarter applications or just finding faster ways to make them vulnerable?</p><h3>The problem</h3><p>In the first half of 2026, reports indicate that 35,872 new vulnerabilities were recorded, representing a 51.3% increase compared to the same period last year.</p><p>That’s a significant increase, and as developers, it’s something we should pay attention to.</p><p>Here is a breakdown of vulnerabilities across different programming languages and ecosystems:</p><pre>[ PHP ] ────────────────► 23% (Web Applications / CMS)<br>[ C / C++ ] ────────────► 19% (OS Kernels / Hardware Drivers)<br>[ JavaScript / TS ] ────► 17% (npm / Dependency Ecosystem)<br>[ Python ] ─────────────► 13% (AI / Machine Learning Ecosystem)<br>[ Java ] ───────────────► 11% (Enterprise Applications)<br>[ Others ] ─────────────► 17% (Go, Rust, and Other Languages)</pre><p>With AI-assisted and agentic coding becoming part of our development workflows, we are writing and shipping code faster than ever.</p><p>But here is the question.</p><p><strong>Are we becoming better at securing the code we ship, or are we just getting faster at introducing vulnerabilities?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ozbvhuXYftZhKEqH.gif" /></figure><h3>So what is the solution?</h3><p>We already know vulnerabilities are not going anywhere. And with the increasing adoption of AI in software development, the amount of code being produced will only continue to grow.</p><p>So how do we stay ahead?</p><p>One approach is something we commonly talk about in DevOps.</p><h4>Shift-Left Security</h4><p>No, I’m not asking you to shift from your current position. 😂</p><p><strong>Shift-left</strong> is a DevOps approach that involves moving activities such as testing, quality assurance, and security earlier in the software development lifecycle.</p><p>Instead of waiting until an application reaches production to discover security issues, we identify and address them during development.</p><p>Think about it this way.</p><p>Would you rather discover a hardcoded API key while writing your code or after your application has been deployed and someone has already exploited it?</p><p>I think we both know the answer.</p><h3>Our Focus: Application Security</h3><p>For this blog, we will focus on three areas where developers can identify potential security vulnerabilities before they reach production.</p><p>And to make this practical, we will answer three questions.</p><p><strong>1. Third-party dependencies</strong></p><p>How can we identify vulnerabilities in the third-party libraries, open-source packages, and container images our applications depend on before pushing code to staging?</p><p><strong>2. Our application code</strong></p><p>How can we identify security weaknesses in our own code, such as hardcoded credentials, unsafe SQL queries, inadequate input validation, and insecure coding practices?</p><p><strong>3. Our running application</strong></p><p>How can we identify security vulnerabilities in our running applications and APIs, including authentication, authorization, session management, and exposed endpoints, before deploying to production?</p><p>To answer these questions, we will explore three security testing approaches:</p><ul><li><strong>SCA</strong> — Software Composition Analysis</li><li><strong>SAST</strong> — Static Application Security Testing</li><li><strong>DAST</strong> — Dynamic Application Security Testing</li></ul><p>The best part?</p><p>We will use open-source tools that you can start using today.</p><p>Let’s get into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*8UD87jk_yGkYI3FW.gif" /></figure><h3>1. Are Your Third-Party Dependencies Secure?</h3><p>Almost every modern application relies on third-party libraries, open-source packages, and container images.</p><p>Whether you are building with React, Django, FastAPI, Node.js, or running your application inside Docker, chances are your application depends on code you did not write.</p><p>And that introduces a challenge.</p><p><strong>How do you know whether those dependencies contain known vulnerabilities?</strong></p><p>This is where <strong>Software Composition Analysis (SCA)</strong> comes in.</p><h4>What Is Software Composition Analysis?</h4><p>Software Composition Analysis is the process of identifying and assessing risks associated with third-party and open-source components used in an application.</p><p>Simply put, it helps answer the question:</p><p><em>Are we importing vulnerabilities into our application through our dependencies?</em></p><h4>For this i will recommend <a href="https://trivy.dev/docs/latest/getting-started/"><strong>trivy</strong></a></h4><p>Trivy is an open-source security scanner that can identify vulnerabilities in dependencies, container images, filesystems, and infrastructure configurations.</p><p>You can run it locally, integrate it into CI/CD pipelines, or use it in containerized and Kubernetes environments.</p><p>For this demonstration, I will use macOS.</p><h4>Step 1: Install Trivy</h4><p>If you have Homebrew installed, run:</p><pre>brew install trivy</pre><h4>Step 2: Scan Your Project</h4><p>Open your terminal and navigate to your project directory.</p><p>Then run:</p><pre>trivy fs --scanners vuln,secret,misconfig ./</pre><p>Here is what we are scanning for:</p><p><strong>Vulnerabilities:</strong> Known security vulnerabilities in supported dependencies.</p><p><strong>Secrets:</strong> Accidentally exposed credentials, tokens, and API keys.</p><p><strong>Misconfigurations:</strong> Potentially insecure infrastructure and configuration files.</p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_A1xl4DD_QPAUzPk4-mUA.png" /></figure><p>You still need to review the findings, understand their severity, determine whether your application is affected, and prioritize remediation.</p><p>Also, keep in mind that a clean scan does not mean your dependencies are completely secure. Trivy primarily identifies issues based on available vulnerability information and supported scanning capabilities.</p><h3>2. What About the Code We Write?</h3><p>Now that we have looked at third-party dependencies, let’s focus on something closer to home.</p><p><strong>Our own application code.</strong></p><p>Even when all our dependencies are up to date, our application can still contain security weaknesses.</p><p>For example:</p><ul><li>Hardcoded credentials and API keys.</li><li>Unsafe SQL queries that could introduce SQL injection vulnerabilities.</li><li>Inadequate input validation.</li><li>Insecure cryptographic practices.</li><li>Improper handling of sensitive information.</li><li>Insecure coding patterns introduced through AI-generated code.</li></ul><p>That’s impressive.</p><p>But how do we know the generated code follows secure coding practices?</p><p>This brings us to our second approach.</p><h4>Static Application Security Testing (SAST)</h4><p>SAST is a security testing approach that analyzes application source code without executing the application.</p><p>It helps identify potentially insecure coding patterns early in the development process.</p><p>Think of it as having an additional reviewer focused specifically on security</p><h4>For this use<strong> </strong><a href="https://docs.semgrep.dev/getting-started/quickstart-ce"><strong>Semgrep community edition</strong></a></h4><p>Semgrep is a static analysis tool that can identify security issues and coding patterns based on predefined rules.</p><p>It supports multiple programming languages, making it useful for developers working across different technology stacks.</p><p>Let’s try it.</p><h4>Step 1: Install Semgrep</h4><p>On macOS, run:</p><pre>brew install semgrep</pre><h4>Step 2: Scan Your Code</h4><p>Navigate to your project directory and run:</p><pre>semgrep scan --config auto</pre><p>This runs a scan using Semgrep’s automatically selected rules.</p><p>You can also configure specific rulesets depending on your application and the security issues you want to identify.</p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7vowkcrHb1_6G1NauUQGQ.png" /></figure><p>You can take this further by customizing rules, integrating Semgrep into your development workflow, and running scans automatically whenever code changes are introduced.</p><p>Some issues, especially those involving business logic, complex authorization flows, and runtime behavior, may require additional testing.</p><p>Which brings us to our final question?</p><h3>3. Is Your Running Application Secure?</h3><p>So far, we have scanned our dependencies and reviewed our application code.</p><p>But there is still one important area we haven’t covered.</p><p><strong>What happens when the application is actually running?</strong></p><p>An application may pass static security scans and still contain vulnerabilities that only become visible during execution.</p><p>For example:</p><ul><li>Missing security headers.</li><li>Insecure session handling.</li><li>Exposed endpoints.</li><li>Authentication weaknesses.</li><li>Certain authorization flaws.</li><li>Improper error handling.</li><li>Security misconfigurations.</li></ul><p>These issues may not always be obvious during code reviews or static analysis.</p><p>This is where our third approach comes in.</p><h4>Dynamic Application Security Testing (DAST)</h4><p>DAST involves testing a running application or API to identify potential security vulnerabilities.</p><p>Unlike SAST, which analyzes source code, DAST interacts with the application while it is running.</p><p>It examines how the application responds to different requests and inputs.</p><h4>Tool: <a href="https://www.zaproxy.org/getting-started/">OWASP ZAP</a></h4><p>For this, I recommend <strong>OWASP ZAP</strong>, also known as Zed Attack Proxy.</p><p>ZAP is an open-source web application security testing tool maintained by an active community.</p><p>It can help developers identify security issues in running web applications and APIs.</p><h4>Getting Started</h4><p>You can install ZAP using its desktop application or run it through Docker and other supported environments.</p><p>For macOS, you can use Homebrew:</p><pre>brew install --cask zap</pre><p>Alternatively, you can download it from the official website.</p><p><strong>Installation guide:</strong> <a href="https://www.zaproxy.org/download/">https://www.zaproxy.org/download/</a></p><p>ZAP’s desktop installation requires a compatible Java runtime, although some installation packages include one.</p><p>Once installed, you can configure ZAP to inspect requests and responses between your browser and your application.</p><p>You can also perform automated scans against applications you own or are authorized to test.</p><p>One important thing to understand is that active security scans send potentially disruptive requests to your application.</p><p><strong>Always test against an authorized environment, preferably staging, rather than blindly scanning production.</strong></p><p>ZAP can identify many common web security issues, but complex authentication, authorization, payment, and business logic vulnerabilities may still require manual security testing.</p><p>I will dive deeper into <strong>DAST and OWASP ZAP</strong> in another blog, including how to configure it and scan an application.</p><h3>Final Thoughts</h3><p>As developers, we spend a lot of time thinking about how to make our applications faster, more scalable, and easier to maintain.</p><p>But security deserves the same attention.</p><p>With the growing number of reported vulnerabilities and the increasing use of AI-assisted development, being proactive about application security is becoming even more important.</p><p>The three tools we have explored — <strong>Trivy, Semgrep, and OWASP ZAP</strong> — are open source and relatively easy to get started with.</p><p>Even better, they can be integrated into CI/CD pipelines, making security checks part of our everyday development workflows.</p><p>Of course, these tools alone will not make an application completely secure.</p><p>Secure architecture, code reviews, proper access controls, threat modeling, and continuous monitoring still matter.</p><p>But they provide a good starting point.</p><p><strong>The goal is not to write code with zero vulnerabilities. The goal is to identify and address as many security risks as possible before they become real problems.</strong></p><p>And that’s a wrap!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*XGrGz3BamQbhYcku.gif" /></figure><p>I’d love to hear from you guys.</p><p><strong>How are you approaching application security in your development workflows?</strong></p><p>Are you using SCA, SAST, DAST, or other tools I haven’t mentioned?</p><p>Let’s learn from each other.</p><p>Cheers!</p><h3>References and Further Reading</h3><ol><li>Vulnerability Statistics — <a href="https://scantitan.com/blog/vulnerability-statistics/">https://scantitan.com/blog/vulnerability-statistics/</a></li><li>Trivy Documentation — <a href="https://trivy.dev/docs/latest/getting-started/">https://trivy.dev/docs/latest/getting-started/</a></li><li>Semgrep Community Edition — <a href="https://docs.semgrep.dev/getting-started/quickstart-ce">https://docs.semgrep.dev/getting-started/quickstart-ce</a></li><li>OWASP ZAP — <a href="https://www.zaproxy.org/getting-started/">https://www.zaproxy.org/getting-started/</a></li><li>OWASP ZAP Downloads — <a href="https://www.zaproxy.org/download/">https://www.zaproxy.org/download/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3990e6dfa1fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Docker production on Contabo]]></title>
            <link>https://medium.com/@vitalismutwiri/deploying-docker-production-on-contabo-ab80809a5623?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab80809a5623</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 18:46:58 GMT</pubDate>
            <atom:updated>2026-08-11T18:46:58.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPZ_FpcyvukOWr9dd0rjNQ.png" /></figure><p>I’ll take you through how I deployed a Docker application inside a Contabo VPS.</p><p>This blog is mainly about <strong>deployment</strong>. I won’t go through setting up Docker locally or building the application. I’m assuming you already have those parts ready.</p><p>The goal is simple:</p><ol><li>Deploy my application to the Contabo instance.</li><li>Connect Cloudflare and handle the domain/DNS side.</li><li>Put Nginx in front of the application.</li><li>Enable HTTPS.</li><li>Make sure the server is reasonably secure.</li></ol><p>Let’s get started.</p><h3>Prerequisites</h3><p>Before we start, make sure you have:</p><ol><li>An application ready to deploy.</li><li>A docker-compose.prod.yml file.</li><li>A Contabo VPS. For this guide, I’m using the lowest instance.</li><li>Your application available on GitHub.</li><li>A domain name.</li><li>And, of course, you’re ready to learn. 😄</li></ol><h3>The Steps We’ll Follow</h3><p>Here’s what we’re going to do:</p><ol><li>Access the VPS through SSH as root.</li><li>Create a new user.</li><li>Set up SSH access for the new user.</li><li>Create a server setup script.</li><li>Run the script.</li><li>Configure the firewall.</li><li>Pull the application from GitHub.</li><li>Configure the environment variables.</li><li>Deploy Docker.</li><li>Configure Nginx.</li><li>Connect the domain.</li><li>Generate the SSL certificate.</li><li>Disable root SSH access.</li><li>Test everything.</li></ol><p>Nothing too complicated. Let’s take it one step at a time.</p><h3>1. Access the VPS Through SSH</h3><p>First, log in to your <a href="https://contabo.com/">Contabo</a> dashboard.</p><p>On the left sidebar, click:</p><p><strong>Servers &amp; Hosting → VPS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FO-jAtMzQtgun1x0jXl_IQ.png" /></figure><p>Select your instance and get the <strong>IP address</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgKXV4kex9vL6lRWYX9YPg.png" /></figure><p>You’ll also need the root password.</p><p>If you don’t have the password, select your instance and click the three dots at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TimV0TO9AD3EQDMpt3lwQ.png" /></figure><p>Choose <strong>Reset Credentials</strong> and set a new password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*0v6HJsGHRANQvZKXSlftTg.png" /></figure><p>Once you’ve done that, open your terminal.</p><p>Run:</p><pre>ssh root@YOUR_SERVER_IP</pre><p>For example:</p><pre>ssh root@123.45.678.912</pre><p>Enter the root password when prompted.</p><p>And there we go — we’re inside the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-nFmOeaPOijFro1O1jOnA.png" /></figure><h3>2. Create a User Instead of Using Root</h3><p>Now that we have access to root, there’s something we need to fix.</p><p>Using root for everything isn’t a good idea.</p><p>We’re going to create another user that we’ll use for our normal deployment work. Whenever we need administrative access, we’ll use sudo.</p><p>I’ll call my user deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*A-RWrqH6bz4TEQE-.gif" /></figure><p>Run:</p><pre>useradd -m -s /bin/bash -G sudo,docker deploy</pre><p>Set a password:</p><pre>passwd deploy</pre><p>Enter your desired password twice.</p><p>Now let’s create the SSH directory:</p><pre>mkdir -p /home/deploy/.ssh<br>chmod 700 /home/deploy/.ssh</pre><p>Now we need to configure SSH.</p><p>Generate an SSH key:</p><pre># Don&#39;t generate a private key on the VPS and copy it back to your laptop.<br># Generate it on the laptop and put only the public key on the VPS<br>ssh-keygen -t ed25519 -C &quot;deploy@example.com&quot;<br></pre><p>Save it under:</p><pre>/home/deploy/.ssh/id_ed25519</pre><p>Then copy the public key into authorized_keys:</p><pre>cp /home/deploy/.ssh/id_ed25519.pub /home/deploy/.ssh/authorized_keys</pre><p>Set the correct permissions:</p><pre>chmod 600 /home/deploy/.ssh/authorized_keys<br>chown -R deploy:deploy /home/deploy/.ssh</pre><p>Now let’s get the private key:</p><pre>cat /home/deploy/.ssh/id_ed25519</pre><p>Copy the entire output.</p><blockquote><strong>Keep this private key private. Don’t send it to anyone or commit it to GitHub.</strong></blockquote><h3>Save the Key on Your Mac</h3><p>On your Mac, create a file for the SSH key:</p><pre>nano ~/.ssh/contabo-deploy</pre><p>Paste the private key.</p><p>Save the file and then run:</p><pre>chmod 600 ~/.ssh/contabo-deploy</pre><p>Now let’s make connecting to the server easier.</p><p>Open your SSH config:</p><pre>nano ~/.ssh/config</pre><p>Add:</p><pre>Host myserver<br>    HostName YOUR_SERVER_IP<br>    User deploy<br>    IdentityFile ~/.ssh/contabo-deploy</pre><p>Now instead of typing the full SSH command, we can simply run:</p><pre>ssh myserver</pre><p>If you successfully get into the server as deploy, we&#39;re good to go.</p><h3>3. Create the Server Setup Script</h3><p>Now let’s prepare the server.</p><p>We could install everything manually, but I prefer using a small script.</p><p>That way, if I need to set up another server later, I don’t have to remember every single command.</p><p>Create the script:</p><pre>nano setup-server.sh</pre><p>Paste the following:</p><pre>#!/bin/bash<br>set -e</pre><pre>echo &quot;[1/5] Updating system packages...&quot;</pre><pre>apt-get update<br>apt-get upgrade -y<br></pre><pre>echo &quot;[2/5] Installing essentials...&quot;</pre><pre>apt-get install -y \<br>    curl \<br>    git \<br>    ufw \<br>    nginx \<br>    certbot \<br>    python3-certbot-nginx \<br>    fail2ban<br></pre><pre>echo &quot;[3/5] Installing Docker...&quot;</pre><pre>if ! command -v docker &gt;/dev/null 2&gt;&amp;1; then<br>    curl -fsSL <a href="https://get.docker.com/">https://get.docker.com</a> | sh</pre><pre>    systemctl enable docker<br>    systemctl start docker<br>else<br>    echo &quot;Docker already installed.&quot;<br>fi</pre><pre>echo &quot;Docker version:&quot;<br>docker --version</pre><pre>echo &quot;Docker Compose version:&quot;<br>docker compose version<br></pre><pre>echo &quot;[4/5] Configuring firewall...&quot;</pre><pre>ufw default deny incoming<br>ufw default allow outgoing</pre><pre>ufw allow 22/tcp<br>ufw allow 80/tcp<br>ufw allow 443/tcp</pre><pre>ufw --force enable</pre><pre>echo &quot;Firewall status:&quot;<br>ufw status<br></pre><pre>echo &quot;[5/5] Creating application directory...&quot;</pre><pre>mkdir -p /home/deploy/apps</pre><pre>chown -R deploy:deploy /home/deploy/apps<br></pre><pre>echo &quot;&quot;<br>echo &quot;==============================&quot;<br>echo &quot; Server setup complete!&quot;<br>echo &quot;==============================&quot;</pre><p>Save the file.</p><p>Then make it executable:</p><pre>chmod 700 setup-server.sh</pre><p>Run the script:</p><pre>sudo bash setup-server.sh</pre><p>Now we wait.</p><p>The script is going to update the server, install the tools we need, install Docker, configure UFW, install Fail2Ban, and create our application directory.</p><p>This saves us from manually running all those commands every time.</p><h3>4. A Quick Note About the Firewall</h3><p>The script also sets up <strong>UFW</strong>, which is our firewall.</p><p>For now, we’re allowing three ports:</p><pre>22  → SSH<br>80  → HTTP<br>443 → HTTPS</pre><p>Everything else coming into the server is denied by default.</p><p>We also installed <strong>Fail2Ban</strong>, which helps protect services such as SSH from repeated brute-force login attempts.</p><p>You can check the firewall with:</p><pre>sudo ufw status</pre><p>You should see something similar to:</p><pre>22/tcp    ALLOW<br>80/tcp    ALLOW<br>443/tcp   ALLOW</pre><h3>5. Pull the Application From GitHub</h3><p>Now that the server is ready, let’s bring our application in.</p><p>For me, I normally pull the application from GitHub.</p><p>First, switch to our deployment user:</p><pre>su - deploy</pre><p>Go to the application directory:</p><pre>cd ~/apps</pre><p>Now generate an SSH key for GitHub:</p><pre>ssh-keygen -t ed25519 -C &quot;your-email@example.com&quot;</pre><p>Once it’s created, display the public key:</p><pre>cat ~/.ssh/id_ed25519.pub</pre><p>Copy the output.</p><p>Go to GitHub and add the key under:</p><p><strong>Settings → SSH and GPG keys</strong></p><p>Make sure you’re adding it to your GitHub account, not the repository settings.</p><p>You can test the connection:</p><pre>ssh -T git@github.com</pre><p>If GitHub recognizes you, we’re ready.</p><p>Now clone the application:</p><pre>cd ~/apps</pre><pre>git clone git@github.com:USERNAME/REPOSITORY.git</pre><p>Then move into the project:</p><pre>cd REPOSITORY</pre><p>And there we go.</p><p>Our application is now on the server.</p><h3>6. Set Up the Environment</h3><p>Before starting Docker, we need to configure our production environment.</p><p>For example:</p><pre>nano .env</pre><p>Add the environment variables your application needs.</p><p>This could include things like:</p><pre>DATABASE_URL=...<br>SECRET_KEY=...<br>API_KEY=...<br><br><br>#then after<br>chmod 600 .env</pre><p>Make sure you don’t accidentally commit your production .env file to GitHub.</p><p>This is where you’ll also configure your database, storage, email service, API keys, and any other production services your application depends on.</p><h3>7. Deploy Docker</h3><p>Now we’re finally ready to deploy.</p><p>From inside your application directory, run:</p><pre>docker compose -f docker-compose.prod.yml up -d --build</pre><p>Docker will build the images and start the containers.</p><p>Once that’s finished, let’s check what’s running:</p><pre>docker compose -f docker-compose.prod.yml ps</pre><p>You can also check your images:</p><pre>docker images</pre><p>If something isn’t working, don’t panic.</p><p>The first thing I normally check is the logs:</p><pre>docker logs CONTAINER_NAME</pre><p>Or, since we’re using Docker Compose:</p><pre>docker compose -f docker-compose.prod.yml logs</pre><p>For a specific service:</p><pre>docker compose -f docker-compose.prod.yml logs SERVICE_NAME</pre><p>Take a moment here and make sure the containers are actually running before moving on.</p><h3>8. Configure Nginx</h3><p>Now our application is running inside Docker.</p><p>But we don’t want users accessing the application directly through something like:</p><pre>http://YOUR_SERVER_IP:8000</pre><p>Instead, we’ll put Nginx in front of it.</p><p>Create an Nginx configuration file:</p><pre>sudo nano /etc/nginx/sites-available/myapp</pre><p>Add:</p><pre>server {<br>    listen 80;</pre><pre>    server_name yourdomain.com;</pre><pre>    location /.well-known/acme-challenge/ {<br>        root /var/www/certbot;<br>    }</pre><pre>    location / {<br>        proxy_pass <a href="http://127.0.0.1:8000;">http://127.0.0.1:8000;</a></pre><pre>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;</pre><pre>        proxy_read_timeout 120s;<br>        proxy_connect_timeout 10s;<br>    }<br>}</pre><p>Replace:</p><pre>yourdomain.com</pre><p>with your actual domain.</p><p>Also, make sure 8000 matches the port your Docker application is exposing.</p><p>Now enable the configuration:</p><pre>sudo ln -s /etc/nginx/sites-available/myapp \<br>    /etc/nginx/sites-enabled/myapp</pre><p>Create the Certbot directory:</p><pre>sudo mkdir -p /var/www/certbot</pre><p>Before reloading Nginx, let’s test the configuration:</p><pre>sudo nginx -t</pre><p>If you get:</p><pre>syntax is ok<br>test is successful</pre><p>then we’re good.</p><p>Reload Nginx:</p><pre>sudo systemctl reload nginx</pre><h3>9. Point Your Domain to the Server</h3><p>Now let’s connect our domain.</p><p>For this example, I’m using Cloudflare.</p><p>Create an <strong>A record</strong> that points your domain to the Contabo VPS IP.</p><p>For example:</p><pre>Type: A<br>Name: api<br>IPv4 address: YOUR_SERVER_IP</pre><p>So:</p><pre>api.myapp.com → YOUR_SERVER_IP</pre><p>Once DNS has propagated, test the domain:</p><pre>curl -I http://api.myapp.com</pre><p>You can also test the server directly:</p><pre>curl -s -o /dev/null -w &quot;%{http_code}&quot; http://YOUR_SERVER_IP/</pre><p>Depending on your application, you might get 200, 301, 404, or another expected response.</p><p>The important thing is that we’re actually reaching the server.</p><h3>10. Generate the SSL Certificate</h3><p>Now let’s get HTTPS working.</p><p>We’ll use Certbot for this.</p><p>Run:</p><pre>sudo certbot --nginx -d api.myapp.com</pre><p>Replace api.myapp.com with your actual domain.</p><p>If everything is configured correctly, Certbot should generate the certificate and update Nginx for us.</p><p>Once it finishes, test HTTPS:</p><pre>curl -I https://api.myapp.com</pre><p>You should get a successful response.</p><p>For example:</p><pre>HTTP/2 200</pre><p>You can also open the domain in your browser.</p><p>If you see your application with the padlock 🔒, we’re doing well.</p><h3>11. Disable Root SSH Access</h3><p>Remember at the beginning when we logged in as root?</p><p>Now that our deployment user is working, we don’t need to leave root SSH access enabled.</p><p><strong>Before doing this, make absolutely sure you can log in using your deployment user.</strong></p><p>From your local machine, test:</p><pre>ssh myserver</pre><p>If that works, we’re safe to continue.</p><p>Open the SSH configuration:</p><pre>sudo nano /etc/ssh/sshd_config</pre><p>Make sure these settings are present:</p><pre>PermitRootLogin no<br>PasswordAuthentication no</pre><p>This means root won’t be able to log in through SSH, and password-based SSH authentication will be disabled.</p><p>You can also apply the changes using:</p><pre>sudo nano /etc/ssh/sshd_config.d/99-hardening.conf<br><br># then add<br>PermitRootLogin no<br>PasswordAuthentication no<br>PubkeyAuthentication yes<br><br># or one line though not advised<br><br>sudo sed -i &#39;s/^#\?PermitRootLogin.*/PermitRootLogin no/&#39; /etc/ssh/sshd_config</pre><pre>sudo sed -i &#39;s/^#\?PasswordAuthentication.*/PasswordAuthentication no/&#39; /etc/ssh/sshd_config</pre><p>Now let’s rate-limit SSH connections using UFW:</p><pre>sudo ufw delete allow 22/tcp<br>sudo ufw limit 22/tcp</pre><p>Restart SSH:</p><pre>sudo systemctl restart ssh</pre><p>Finally, let’s make sure Fail2Ban is running:</p><pre>sudo systemctl status fail2ban</pre><h3>That’s All</h3><p>And that’s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*AW6nXbVmfFpfFMYt.gif" /></figure><p>We started with a fresh Contabo VPS and ended up with:</p><ul><li>Docker running our application</li><li>A dedicated deployment user</li><li>SSH key authentication</li><li>Root SSH access disabled</li><li>UFW configured</li><li>Fail2Ban running</li><li>Nginx configured</li><li>Our domain pointing to the VPS</li><li>HTTPS enabled</li><li>Our application running in production</li></ul><p>There are still a few things we can improve from here — automated deployments, backups, monitoring, Docker health checks, Cloudflare configuration, database backups, and maybe even zero-downtime deployments.</p><p>You can leave a comment on how we can do it better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab80809a5623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Amazon Q Developer create applications?]]></title>
            <link>https://medium.com/@vitalismutwiri/can-amazon-q-developer-create-applications-f0f520b5f7aa?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f520b5f7aa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[amazon-q-cli]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 18:17:30 GMT</pubDate>
            <atom:updated>2025-09-26T18:17:30.866Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noSNs09RdSxXqyHiShHiaw.png" /></figure><p>We all know Amazon Q Developer hasn’t hit the same revenue highs as some competitors, but that doesn’t mean it lacks potential.</p><p>So Let’s Build with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYIX1eS6_IGDT-NS1mMuvQ.png" /></figure><h4>Background Story</h4><p>As developers, we’ve all had those marathon days (or nights). You’re in the zone, fueled by coffee, and running on 2–4 hours of sleep. Music becomes your companion, but here’s the problem:</p><ul><li>You change playlists depending on your coding mood.</li><li>A bug or deep focus shifts your vibe, so you tab out to switch music.</li><li>That quick detour breaks your flow — context lost, productivity dips.</li></ul><p><strong>What if the music adapted to your coding flow automatically?</strong><br>Imagine opening Visual Studio Code and the music just <em>starts</em> in the background, adjusting to your productivity levels without you ever leaving the editor. That’s the idea behind my extension. I see you nodding<br>@Kirimi Gitonga my friend nodded also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*QIOptFiu4pXVFvsq.gif" /></figure><h4><strong>Let’s go back 10 months ago.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*JzkHbGw1oAc1oZsj.gif" /></figure><p>10 months ago i was privileged to attend Amazon Q Coin challenge.<br>The same week i had coded overnight and faced the problem the next day of work.</p><p>So i showed up for the challenge to build an app using Amazon Q developer in 30 minutes. ( find the<a href="https://www.linkedin.com/posts/vitalismutwiri_aws-awscommunity-activity-7256554527993057280-1MVJ?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAADq9LPkBTFPfZSQ2YyU3uqg230KthOyhxu8"> post here</a> ), and how best to solve your problems then building them. I used last.fm, Puppeteer and Python.</p><p><strong>So why am i building it 10 months later?</strong><br>1. I shared with <a href="https://za.linkedin.com/in/veliswa-boya?trk=public_post_comment_actor-name">Veliswa Boya</a> i would complete the extension.<br>2. To share it with the community.<br>3. Challenge myself to do it fully again using Amazon Q Developer and how better to do it than with the command line.</p><p>So now i will walk you through the journey once more walking you through my thoughts and approach.</p><h4>The Problem</h4><p>Developers get disrupted when shifting between playlists during coding sessions (context lost, extra friction, wasted time).<br>How might we help developers reduce the time (and cognitive cost) of switching playlists between code sessions?</p><h4>Understanding the MVP</h4><p>What would we call success.</p><p>1. Music launches when the editor opens.</p><p>2. Productivity is tracked in the background.</p><p>3. Music changes automatically when productivity rises or falls.</p><p>4. Playlist control stays <em>inside the editor</em> (status bar + shortcuts).</p><p>5. One-click stop/resume without leaving VS Cod</p><h4>Approach and tools</h4><p>I took a <strong>modular approach</strong>: each function handles one responsibility.</p><p>Since I used <strong>Amazon Q Developer</strong>, I followed <strong>spec-driven development</strong> — defining clear boundaries and asking Q to generate tasks.</p><p><strong>Tech stack:</strong></p><p>a, Switched from Python to <strong>Node.js</strong>.</p><p>b, Integrated with <strong>Last.fm</strong> API.</p><p>c, Used <strong>Puppeteer</strong> for browser automation.</p><p>The whole interaction took less than 3 <strong>hours</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAL_xuWbooTsSsLGEAPZhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIFxAGGue53kOHkF8AUWhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSgpWli0j2XVlEZvUtBowg.png" /></figure><h4>Shortcoming</h4><p>So i created the VSIX file and uploaded to Microsoft. and tried it on two developers.</p><p>1. So the extension by default check your default Browser and launches it using Puppeteer, so one of the observations was it does not launch on Edge, but i have corrected that and will update it</p><p>2. Currently it only works with last.fm, but will look forward to add spotify</p><p>3. I will also be updating so that it asks for last.fm api currently it uses same key embedded on it.</p><h4>How to access the extension.</h4><p>You can use this link to access the extension.<br><a href="https://marketplace.visualstudio.com/items?itemName=vitalis.adaptive-coding-music">https://marketplace.visualstudio.com/items?itemName=vitalis.adaptive-coding-music</a></p><p>Or on extensions <br>Search for <br>Music Companion and choose the extension without a logo.</p><h3>Final Thoughts</h3><p>Amazon Q Developer isn’t just an AI assistant for code — it can actually help you build real applications and extensions fast. The experience has been smooth, and if you’re curious, give Q Developer a try and let me know your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f520b5f7aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Not to Build a Community Website: Lessons from AWS Community Day Kenya]]></title>
            <link>https://medium.com/@vitalismutwiri/how-not-to-build-a-community-website-lessons-from-aws-community-day-kenya-d03b59b87676?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03b59b87676</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[trends]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 07:20:56 GMT</pubDate>
            <atom:updated>2025-09-16T07:20:56.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKhxK0_gR7vwNnq7qOJDEA.png" /><figcaption>Aws Community Day Kenya README</figcaption></figure><p>In this post, I’ll share what we learned building the AWS Community Day Kenya website — fast. This isn’t a playbook, but a real-world example of decision-making under pressure.</p><p>What i will be sharing is our use case and the thinking behind every decision made, not a playbook but a reference to making your decision.</p><p><strong>I will approach it in three steps</strong><br>1. Assess<br>2. Mobilize<br>3. Build as you go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVPTg6LEX_Y_jeUzXsefgQ.png" /></figure><p>Let’s take an example you were attending the AWS summit Johannesburg 2025, <br>you needed to plan — you needed first to register, identify the hotel to stay, airplane to use, identify personal things you need to carry based on the climate and much more,</p><p>then prepare, that is book that hotel, get the tickets for the plane, buy briefcases and personal stuff needed and much more then be ready to travel.</p><p>then travel <br>The same applies almost in all of our lives activities, and in building apps or businesses it’s so important, you can term it as “Build with context”, or simply “First solve the problem, then write the code”.</p><p><strong>Let’s go to the first step</strong></p><h3><strong>Assess</strong></h3><p>Simply evaluate your situation, in our case, was<br><strong> a, Why did we need a new website instead of using the existing one?</strong><br><strong>b, What did we want it to do?</strong><br><strong> c, How would it scale or serve future community events? (Scalability and robustness)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*P-AGxJ2_C_9ztaW-.gif" /></figure><p>The assessment was:<br><strong>a. Why a new site?</strong> The old one had cluttered code. It wasn’t ours. It didn’t reflect our values or vision.<br><strong>b. What did we want?</strong> A vibrant site showcasing past events, optimized for mobile, accessible, and up to modern standards.<br><strong>c. Will it scale?</strong> We needed something modular, SEO-friendly, and easy to deploy. Thankfully, AWS had us covered on hosting.</p><p>Now you may be asking the title of the blog was focused on what not to do but we are covering what to do, all i have to say is “The opposite is true”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*pUBc-uD2oL0Yj_-r.gif" /></figure><p><strong>Step 2</strong></p><h3>Mobilize</h3><p>The second is a very critical stage, it is similar to prepare, I know you have already heard that “preparedness meets opportunity”, same applies with Mobilizing, you need to Mobilize your resources based on need and most critical thing TIME.</p><p>The question was simply how to build the site in the shortest time possible. <strong>So we Mobilized our resources</strong>, <strong>Here is what we had:</strong></p><ul><li>A working (though messy) website</li><li>Examples from other AWS community sites</li><li>A rough idea of what we wanted</li></ul><p>If you are in tech, you already know the worst thing to build is an idea, because it is not defined, it does not have boundaries, as Jason Fried call it “Grab-bags”.</p><p>How we approached it was simply find a site that similiar to what we call energetic or vibrant and start from there.</p><p><strong>Copying is Okay<br></strong>Remember with ideas you know it when you see it. So we went full in evaluating existing sites, Lucky enough, we settled on Bengaluru previous community day website. We did not copy everything it was a guide to what we needed.</p><p><strong>Reuse</strong><br>We looked on the previous website, cleanup and copied what was useful.</p><p><strong>Understand the usecase<br></strong>We used Javascript HTML and CSS, because, we were more focused on content and SEO and how best to do it than use multi page application. <br>Understand more on <a href="https://youtu.be/Cifkb-ZVps4?si=6pCxFzSSDxsqXz31">that here</a></p><p><strong>Step 3</strong></p><h3><strong>Build as you go</strong></h3><p>We did not focus on the perfect full site but we focused on what was necessary and added sections and functionality as needed though we had mapped out all the sections we needed.</p><p>Principle number 4 Of Kaizen — Let go of perfectionism and take an attitude of iterative adaptive change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mL7APQ1-9E8i_iLZOJrCFg.png" /></figure><p><strong>So, what <em>not</em> to do?</strong></p><ul><li><strong>Don’t skip the assessment — context is everything.</strong></li><li><strong>Don’t build in isolation — mobilize your resources.</strong></li><li><strong>Don’t wait for perfection — start, then iterate.</strong></li></ul><p>I hope this was helpful — it was definitely fun to write.<br>This marks my 50th blog on Medium!</p><h4>Shoutouts</h4><p><strong>Thank you to</strong> <br>1. Adeline Makokha (AWS Hero)<br>2. Mark Orina (ISOC)<br>3. Tony Gitonga<br>4. Kevin Tuei<br>5. Jacob Moracha<br>6. Farah Abdi<br>7. Sandra Mbithe<br>8. Antonny Ochieng<br>9. Bengaluru AWS Community<br>10. Every single community member</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03b59b87676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Trick to Clear Cached Data in Next.js]]></title>
            <link>https://medium.com/@vitalismutwiri/one-trick-to-clear-cached-data-in-next-js-f1208d323b3c?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1208d323b3c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 18:34:58 GMT</pubDate>
            <atom:updated>2024-12-23T18:34:58.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yZ1DiGnv0ubDpOu2.png" /></figure><p>Earlier this year, I spent countless hours debugging an issue that ultimately led me to discover a simple yet powerful solution in Next.js. In this blog, I’ll share that solution — a hidden gem that works like magic. Let’s dive in! 🚀</p><h3>A Quick Story: Hammering the Right Spot</h3><p>Ever heard the story about the ship that couldn’t be fixed?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*8i2M6II8BQ6ME_5z.gif" /></figure><p>The owner tried every mechanic, but no one could solve the issue. Finally, he called in a renowned expert. The expert inspected the ship, grabbed a hammer, and tapped a specific spot. Instantly, the problem was fixed.</p><p>When the owner saw the bill, he asked why it was so expensive for a single hammer strike. The expert replied, “You’re paying for my knowledge of where to hammer.”</p><h3>Why This Story Matters</h3><p>As developers, we often encounter bugs that consume time and resources, only to discover the fix lies in a single line of code. This experience reminded me of that story — sometimes, it’s not about how much effort you put in but knowing precisely where to focus your efforts.</p><h3>The Caching Conundrum</h3><p>Caching has always been a double-edged sword in software development. It improves performance but introduces complexities like stale data. Developers face a delicate balancing act:</p><ul><li><strong>What</strong> data should be cached?</li><li><strong>When</strong> should caching occur?</li><li><strong>How long</strong> should data remain cached?</li><li><strong>Where</strong> should the cache be stored?</li></ul><p>Modern frameworks have introduced solutions to manage caching effectively, but the challenge persists.</p><h3>Re validation</h3><p>Revalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information.</p><h3>Next.js and Caching in 2024</h3><p>Next.js, a popular JavaScript framework, has been at the forefront of caching innovations. By default, it caches all fetched data, which enhances user experience. However, earlier versions of Next.js often required extra steps to handle caching issues.</p><p>In their latest updates, Next.js introduced improvements to caching mechanisms, but developers still need to know how to disable caching when necessary.</p><h4>Back to my problem early in the year.</h4><p>At the start of the year, I was working on a project using Cloudinary. The app allowed users to upload images, optimize them, create collages, and more — all in real time. However, I ran into a problem: Next.js was caching every fetched request, and clearing the cache wasn’t straightforward.</p><p>I tried several solutions, including:</p><ol><li>Removing the default force-cache behavior.</li><li>Setting revalidation to zero.</li></ol><p>Despite these efforts, the issue persisted. Then, I discovered the ultimate fix:</p><h3>The Gem of a Solution</h3><p><strong>Drumroll, please…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Wl00yg_18YcR2cC2.gif" /></figure><pre>export const revalidate = 0;</pre><p>Yes, it’s that simple.</p><h3>How It Works</h3><p>Add this line at the end of your data-fetching logic — whether in server actions or route handlers. It disables caching entirely, ensuring your app always fetches fresh data.</p><p>Making it even better you use it when you want it and it does not affect the whole project only that part needing Revalidation.</p><h3>Why I’m Sharing This</h3><p>I recently worked on a blog-posting app using the latest Next.js version. While testing in production, I noticed some issues with data updates. Instead of debugging for hours, I remembered my trusty gem. I added export const revalidate = 0 to the route handlers, and it instantly worked!</p><p>If you’re grappling with caching headaches, this one line might save you a lot of time.</p><h3>Final Thoughts</h3><p>Debugging is part of the developer journey, but knowing where to “hammer” makes all the difference. I hope this tip saves you time and effort.</p><p>Cheers and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1208d323b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is computational complexity and Big O part 2?]]></title>
            <link>https://medium.com/@vitalismutwiri/what-is-computational-complexity-and-big-o-part-2-4a26bac1f96c?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a26bac1f96c</guid>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 07:59:46 GMT</pubDate>
            <atom:updated>2024-12-10T07:59:46.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1witF7trBbG17GZ3.png" /></figure><p>In a previous blog, I wrote about the two-pointer algorithm, but I didn’t dive into how efficient it is as the input size grows. Today, let’s explore how to measure the efficiency of an algorithm. Before revisiting the two-pointer algorithm, it’s important to understand computational complexity and Big O notation. (Check out part 1 of computational complexity and Big O <a href="https://medium.com/@vitalismutwiri/what-is-computational-complexity-and-big-o-36cd043d8554">here</a>)</p><p>Lastly we covered Constant O(1), Logarithmic O(Log n), <br>Today we will be covering Linear O(n), Log linear O(n Log n), Quadratic O(n²) and Exponential O(2n).</p><p>Let’s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*NDReabfszeuIBPsu" /></figure><h4>Linear O(n)</h4><p>In the simplest sense, linear refers to something extending in a straight line. In terms of computational complexity, if you were to graph the relationship between the input size n and the number of operations, a linear time complexity graph would form a straight line.</p><p>What this means is: the number of operations scales directly with the size of n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*KHMhPt_wv9dTjsCG.png" /></figure><p>Let’s make this more relatable:<br>Imagine you’re a footballer with 10 balls. Your task is to kick each ball once. Here’s the math:</p><p>Balls: 10<br> Operations (kicks): 10</p><p>Since the number of operations (kicks) matches the number of balls, the complexity is linear — it scales 1:1 with the input size.</p><p><strong>What are some operations you can do with Linear <br>1. </strong>Copying elements<br>2. Inserting or deleting items<br>3. Iterating through a dataset</p><p><strong>The algorithm here will be</strong><br>1. Linear search algorithm</p><h4>Log Linear or (Quasi-linear) O(n log n)</h4><p>Now, things get a bit more interesting. Log-linear complexity combines two behaviors:</p><ul><li><strong>Linear O(n):</strong> We process nnn items.</li><li><strong>Logarithmic O(log⁡n):</strong> For each item, we perform a logarithmic operation.</li></ul><h4>Example:</h4><p>Let’s say you have two tubes of balls. You want to compare every ball in Tube 1 with its counterpart in Tube 2.</p><ul><li>Searching Tube 1 takes O(n).</li><li>For each ball in Tube 1, finding its counterpart in Tube 2 takes O(log⁡n).</li></ul><p>Multiply these together, and you get O(nlog⁡n).</p><p><strong>Properties of Log linear</strong></p><ol><li>For each operation of the input data has logarithmic time complexity</li></ol><h4>Operations</h4><ol><li>Sorting a list of elements</li></ol><p><strong>Algorithms</strong></p><ol><li>Merge sort</li><li>Heap sort</li><li>Cube sort</li></ol><h4>Quadratic O(n²)</h4><p>First remember Big O notation classify algorithms according to how their runtime or space requirements grow as the input size grows.</p><p>The purpose of reminding you this is to understand how the quadratic time grows as the input size grows.</p><p>With <strong>quadratic complexity</strong>, the runtime scales as the square of the input size n: n².</p><h4>Example:</h4><p>Imagine nested loops:</p><ul><li>The outer loop runs nnn times.</li><li>For every iteration of the outer loop, the inner loop also runs nnn times.<br>This results in n×n=n² operations.</li></ul><p><strong>Properties of quadratic</strong></p><ol><li>Perform a linear time operation on each value of the input data.</li></ol><p><strong>Operations</strong></p><ol><li>Quadratic algorithms typically involve <strong>nested loops</strong>, where each loop depends on the input size.</li></ol><p><strong>Algorithm</strong><br>1. Bubble sort<br>2. Tree sort<br>3. Selection sort<br>4. Insertion sort<br>5. Bucket sort<br>6. Quick sort</p><h4>Exponential time O(2n)</h4><p>Remember what Big O notation does (Classify algorithm according to how their runtime and space requirements grow as the input size data grow).</p><p><strong>Property</strong><br>For exponential the growth doubles on each addition to the input data set</p><h4>Example:</h4><p>Think of the <strong>Tower of Hanoi</strong> problem or <strong>Recursive Fibonacci</strong>. Every time you add a disk (or an element), the number of operations required doubles.</p><p><strong>Algorithm</strong></p><p>Recursive Fibonacci</p><p><strong>Wrapping up</strong><br>Understanding computational complexity is key to writing efficient algorithms. By analyzing how the runtime grows with input size, you can predict performance and make better choices.</p><p>Next time, we’ll go deeper into these algorithms and see some practical examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*J46sFbakZGRZ-h2u" /></figure><h3>Let’s Connect!</h3><p>Follow me on <a href="https://github.com/svitalis123">Github</a><br>Check out my <a href="https://portfolio-v1-rouge-five.vercel.app/">Portfolio.<br>Contact me for any collaboration in my Portfolio</a><br>Check out <a href="https://portfolio-v1-rouge-five.vercel.app/blogs">my blogs from my Portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a26bac1f96c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is computational complexity and Big O ?]]></title>
            <link>https://medium.com/@vitalismutwiri/what-is-computational-complexity-and-big-o-36cd043d8554?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/36cd043d8554</guid>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[today]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 08:58:48 GMT</pubDate>
            <atom:updated>2024-11-21T08:58:48.430Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is computational complexity and Big O ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*peMzuaGDGuneHfZG.png" /></figure><p>In a previous blog, I wrote about the two-pointer algorithm, but I didn’t dive into how efficient it is as the input size grows. Today, let’s explore how to measure the efficiency of an algorithm. Before revisiting the two-pointer algorithm, it’s important to understand computational complexity and Big O notation. (Check out the blog <a href="https://medium.com/@vitalismutwiri/revolutionizing-real-estate-how-two-pointer-algorithms-maximize-investments-b5ca547acc91">here</a>)</p><p><strong>Prerequisites<br></strong>To follow along, a basic understanding of algorithms and data structures is helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*s3Go-B20MsLiL9kH.gif" /></figure><h4><strong>Computational Complexity</strong></h4><p>What is it?<br>In simple terms, computational complexity is the amount of work needed to perform a specific task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKVO6_ajTwlCPmzqcxKlLA.png" /></figure><p>Imagine John pushing a wheelbarrow from Point A to Point B. The energy he uses gives us an idea of the work required. Computational complexity is similar, but instead of wheelbarrows, we’re measuring the resources a computer uses to perform a task.</p><p>You now grasp the idea, but for computational Complexity we are not moving wheelbarrows, let’s get to a deeper definition.</p><p>Computational complexity — it is the measure of the amount of computational resources(like time and memory) needed for a particular task.</p><p>We have now replaced work with more specific word computational resources.</p><p>If you quickly peep to your dictionary computational means relating to computer.</p><p>So this means we will use computer resources to perform a particular task.</p><blockquote>I am keeping this simple so that we can get the understanding.<br>Computational complexity — It is the measure of the amount of the computational resources needed for a particular task</blockquote><p>With this understanding we can go to the next definition.</p><h4>Big-O</h4><p>What is Big-O — in the simplest terms it is the measure of how efficient an algorithm is?</p><ul><li>it Categorizes algorithm on how their time and space requirements grow as the input size grows</li></ul><p>We have introduced Time and Space complexity, let’s take a step back and define the words introduced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*VM6_xnVOLpfM9tcu.gif" /></figure><p><strong>Time Complexity<br>-</strong> What is time complexity — it is how long it takes to run your function in computational steps.</p><p>We will talk about computational steps later, taking the example of John previously is how long John takes to take is wheelbarrow from point a to b.</p><p><strong>Space complexity<br>- </strong>what is space complexity — it is the memory the function uses.</p><blockquote>So we now know time complexity is the time taken to run the function in computational steps and space complexity is the memory used by the function</blockquote><p>Let’s connects the dots.<br>Big O— Categorize algorithms on how their time and space requirements grows as the input size grows.</p><blockquote>Replacing the terms we are categorizing algorithm on the time the algorithm takes to do a particular task and the memory it uses while doing the task.</blockquote><p>One more thing, we are doing comparison,</p><p>So what is this comparison we are doing?<br>lets take a simple function taking in objects and doing a for in loop and returning each key and value</p><pre>const ages = {&quot;mary&quot;:20, &quot;peter&quot;: 30}<br><br>function showAges(ages){<br>  for (const a in ages) {<br>    alert(&quot;name:&quot;, a, &quot;ages:&quot;, ages[a])<br>  }<br>}<br><br>showAges(ages);</pre><p>So that we do the comparison <br>1. We must understand that Big O is used in algorithm to represent the upper bound or what we can call the Worst case scenario.</p><p>To identify the worst case scenario we must do some comparison right?</p><p>E.g what if the ages where a million records how long would it take?? it’s a question we should answer.</p><p>And what i have just explain; is the last part of Big O definition (“INPUT SIZE GROWS”)</p><p>It categorize algorithm as how their time and space requirements grow as the <strong>INPUT SIZE</strong> grows</p><p>Now how do you calculate the Big O ??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*UA33Kj5PhkOWPsrh.gif" /></figure><h4>How to calculate Big O</h4><ol><li>Split your algorithm into operations</li><li>Calculate Big O for each operation</li><li>Add up Big O from each operation</li><li>Strip the constants</li><li>Find the highest order term</li></ol><p>Let’s take an example of the function we used</p><p><strong>Step 1: Split your algorithm into operations</strong></p><pre>// an operation<br>const ages = {&quot;mary&quot;:20, &quot;peter&quot;: 30}<br><br>function showAges(ages){<br>//an operation<br>  for (const a in ages) {<br>    // an operation<br>    alert(&quot;name:&quot;, a, &quot;ages:&quot;, ages[a])<br>  }<br>}<br><br>showAges(ages);</pre><p><strong>Step 2: Calculate Big O for each operation</strong></p><pre>// an operation<br>const ages = {&quot;mary&quot;:20, &quot;peter&quot;: 30} O(1) constant<br><br>// let&#39;s assume i have an array here<br>const mydummyarray = [1, 2, 3, 4] 0(1)<br><br>// let&#39;s find half of it<br>const halfofarray = mydummyarray.length/2 O(n/2)<br><br>function showAges(ages){<br>//an operation<br>  for (const a in ages) { O(n) linear<br>    // an operation<br>    alert(&quot;name:&quot;, a, &quot;ages:&quot;, ages[a]) O(1)<br>  }<br>}<br><br>showAges(ages);</pre><p>i have added the array and calculating it’s half so that we can explain the aspect of stripping</p><p><strong>Step 3: Add up the Big O from each operation</strong></p><pre>O(1 + 1 + n/2 + n + 1)</pre><p><strong>Step 4: Strip the constants</strong></p><pre>Stripping 1, 1/2 we remain with<br><br>O(n)</pre><p><strong>Step 5: Find the Highest order term</strong></p><pre>O(n)</pre><p>What are O(1), O(n)</p><p>Let’s now talk about Big O functions.</p><h4>Big O functions</h4><p>We have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*rqtXbI0LiaUJ3uO1hg_ORw.png" /></figure><p>Constant — O(1)<br>Logarithmic O(Log n)<br>Linear O(n)<br>Log Linear O(n Log n)<br>Quadratic O(n²)<br>Cubic O(n³)<br>Exponential O(2^n)</p><p>For this blog i will explain the first two:</p><h4>Constant O(1)</h4><p>As the name suggest is something that does not change.<br>Lets quickly look at the properties of constant<br>1. The execution time is not dependent on input data. <br>2. The time complexity does not change.</p><p>Examples are</p><ol><li>Get (read an index e.g get index or an array array[1])</li><li>Set (assigning e.g const age = 40 )</li><li>Arithmetic operations (this are for example a+b)</li><li>Comparison (e.g a===1)</li></ol><p>Now we get</p><pre>// an operation<br>const ages = {&quot;mary&quot;:20, &quot;peter&quot;: 30} O(1) constant<br><br>// let&#39;s assume i have an array here<br>const mydummyarray = [1, 2, 3, 4] 0(1)</pre><p>On the above example notice we do set Ages to the set or mydummyarray to the array, which is constant O(1).</p><h4>Logarithmic (O(Log n))</h4><p>To understand it let’s look at it’s properties.</p><ol><li>The input data size reduces in each step</li><li>You don’t need to look up all values</li><li>The next action done will only be done on one of the possible elements</li></ol><p>so let’s take an example <br>In binary search<br>We first get the length of the data.<br>Get the middle point <br>Set — our starting and ending point<br>Then check the value we are searching if its on the side of the starting to middle or from middle to the end,</p><p>With this you now understand first property which is — in each step the data input size reduces, — Because if the value we are searching is in between the first and the middle, we let go of the middle to the end, because our value can’t be there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*osvcxb3ib4GiELko.jpg" /></figure><p>Second property as well is covered because we wont look up for the value in the other half.</p><p>And lastly the next action is only performed on one of the possible elements which is to look the first half or the second half.</p><p>Logarithmic is mostly used in divide and conquer approaches.</p><h4>Wrapping Up</h4><p>Understanding computational complexity and Big O is key to writing efficient code. Today, we covered:</p><p>What computational complexity is.<br> The basics of Big O notation.<br> How to calculate Big O.<br> Examples of common Big O functions like O(1) and O(log n).</p><p>In the next blog, we’ll dive deeper into other Big O functions</p><h4>Let’s Connect!</h4><p>Follow me on <a href="https://github.com/svitalis123">Github</a><br>Check out my <a href="https://portfolio-v1-rouge-five.vercel.app/">Portfolio.<br>Contact me for any collaboration in my Portfolio</a><br>Check out <a href="https://portfolio-v1-rouge-five.vercel.app/blogs">my blogs from my Portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36cd043d8554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Custom Clerk Auth Forms and Google authentication with NextJS, and Tailwind]]></title>
            <link>https://blog.devgenius.io/how-to-create-custom-clerk-auth-forms-and-google-authentication-with-nextjs-and-tailwind-98aeea966248?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/98aeea966248</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 07:46:51 GMT</pubDate>
            <atom:updated>2024-11-19T12:47:38.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*STBxRIHNfpne19Rz.png" /></figure><p>Recently, while working on a project, I needed to set up a custom authentication system that matched our brand’s style. I decided to create a custom Clerk Auth form with our own design. To get started, I looked for resources and guides, but most didn’t quite meet my needs.</p><p>My specific requirements were:</p><ol><li>A sign-in option using a code for verification.</li><li>Google authentication for a smooth, one-click sign-in.</li></ol><p>After diving into Clerk’s documentation, I found that using JavaScript components was the best approach to achieve this (Clerk also offers “Clerk Elements,” but it’s currently in beta).</p><p>In this post, I’ll walk you through how to set up user authentication with a verification code during sign-up and how to add Google sign-up options, using an example to guide each step.</p><p><strong><em>N/B — for google ensure you have a Google developer account</em></strong><a href="https://clerk.com/docs/authentication/social-connections/google#add-google-as-a-social-connection"><strong><em> here is a guide for that</em></strong></a></p><p><strong>Steps we will cover</strong></p><ol><li>Setting Up Clerk and Next.js Hooks</li><li>Initializing State Variables</li><li>Loading State Management</li><li>Handling Sign-Up with Email</li><li>Handling Google Sign-Up</li><li>Handling Verification Code Submission</li><li>Handling Resend Verification Code</li><li>Loading and Conditional Rendering</li></ol><blockquote>This is more of functionality, for forms you can create for yourself.<br>here is my relative path<br>app/sign-up/[[…sign-up]]/page.jsx</blockquote><p>Are you Ready?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ttaBXUqEp0h0g5E8.gif" /></figure><ol><li><strong>Setting Up Clerk and Next.js Hooks</strong></li></ol><p>We will import hooks from Clerk and Next.js, allowing us to handle sign-up and authentication within the app. These hooks simplify managing authentication states and redirecting users upon successful sign-up.</p><pre>import { useState, useEffect } from &quot;react&quot;;<br>import { useSignUp, useAuth } from &quot;@clerk/nextjs&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;</pre><p>Remember to add use-client</p><p><strong>2. Initializing State Variables</strong><br>We will set up state variables to manage error messages, verification state, email tracking and whether content should display. By managing these states, the app provides clear feedback during each step of the sign-up process, ensuring users know exactly what’s happening.</p><pre>const [error, setError] = useState(&quot;&quot;);  const [verifying, setVerifying] = useState(false);<br>const [email, setEmail] = useState(&quot;&quot;);<br>const [isCompleting, setIsCompleting] = useState(false);<br>const [shouldShowContent, setShouldShowContent] = useState(false);</pre><p><strong>3. Loading State Management</strong></p><p>The next step is to check if the app is loaded and whether the user is signed in. We will display content if the app is fully loaded avoiding partially loaded components or errors. Always verify the app’s loading state before allowing user interactions to improve user experience.</p><pre>useEffect(() =&gt; {<br>if (!isLoaded) return;<br>if (isSignedIn) {<br>    router.replace(&#39;/&#39;);<br>  } else {<br>    setShouldShowContent(true);<br>  }<br>}, [isLoaded, isSignedIn, router]);</pre><p><strong>Take a moment and implement that, then be ready for the real stuff.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*WoIZIBsBkgsDPH6a.gif" /></figure><p><strong>4. Handling Sign-Up with Email</strong></p><p>In this step we will create a new user with the provided email and start the verification process.<br>The email verification is key to preventing fake accounts and ensuring account security.</p><pre>const handleSignUp = async (formData) =&gt; { <br>if (!isLoaded) return;<br>  try {<br>    await signUp.create({<br>      firstName: formData.firstName,<br>      lastName: formData.lastName,<br>      emailAddress: formData.emailAddress,<br>      strategy: &quot;email_code&quot;<br>    });<br>    setEmail(formData.emailAddress);<br>    setVerifying(true);<br>  } catch (err) {<br>    if (err.code === &#39;form_identifier_exists&#39;) {<br>      setError(&quot;An account with this Google email already exists. Please sign in instead.&quot;);<br>    } else {<br>      setError(err.errors[0].message);<br>    }<br>  }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*qF2DyELjFDkyHuFK.gif" /></figure><p><strong>5. Handling Google Sign-Up</strong></p><p>Let’s handle individual signing up with Google, this reduces sign-up friction by allowing users to sign up without filling out forms.</p><pre>const handleGoogleSignUp = async () =&gt; {  <br>if (!isLoaded) return;<br>try {<br>    await signUp.authenticateWithRedirect({<br>      strategy: &quot;oauth_google&quot;,<br>      redirectUrl: &quot;/sign-in&quot;,<br>      redirectUrlComplete: &quot;/&quot;,<br>    });<br>  } catch (err) {<br>    if (err.code === &#39;authentication_failed&#39;) {<br>      setError(&quot;Authentication with Google failed. Please try again.&quot;);<br>    } else if (err.code === &#39;form_identifier_exists&#39;) {<br>      setError(&quot;An account with this Google email already exists. Please sign in instead.&quot;);<br>    } else {<br>      setError(err.errors[0]?.message || &quot;An error occurred during Google sign-up. Please try again.&quot;);<br>    }<br>  }<br>};</pre><p><strong>6. Handling Verification Code Submission</strong></p><p>Let’s go back and handle people signing up with email, let’s ensure they verify their accounts</p><pre>const handleVerify = async (code) =&gt; {<br>if (!isLoaded) return;<br>setIsCompleting(true);<br>  try {<br>    const completeSignUp = await signUp.attemptEmailAddressVerification({ code });<br>    if (completeSignUp.status === &quot;complete&quot;) {<br>      await setActive({ session: completeSignUp.createdSessionId });<br>      router.replace(&#39;/&#39;);<br>    } else {<br>      setIsCompleting(false);<br>      setError(&quot;Verification failed. Please try again.&quot;);<br>    }<br>  } catch (err) {<br>    setError(err.errors[0].message);<br>    setIsCompleting(false);<br>  }<br>};</pre><p><strong>7. Handling Resend Verification Code</strong></p><p>Let’s handle if the verification expires or they don’t receive it, we can handle this by re-sending the code.</p><pre>const handleResendCode = async () =&gt; {<br> if (!isLoaded) return;<br>try {<br>    await signUp.prepareEmailAddressVerification({ strategy: &quot;email_code&quot; });<br>  } catch (err) {<br>    setError(&quot;Failed to resend code. Please try again.&quot;);<br>  }<br>};</pre><p><strong>8. Loading and Conditional Rendering</strong></p><p>Let’s handle different parts of the screen loading.</p><pre>if (!shouldShowContent || isCompleting || !isLoaded || isSignedIn) {  <br>return (<br>&lt;div className=&quot;fixed h-screen top-0 left-0 right-0 bottom-0 flex flex-col gap-6 justify-center items-center bg-card dark:bg-card z-[100]&quot;&gt;<br>      &lt;Your loader /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Finally <br>Here is the return with the different components</strong></p><pre>return (&lt;div className=&quot;&quot;&gt; {!verifying ? (&lt;yoursignupform onSubmit={handleSignUp} onGoogleSignUp={handleGoogleSignUp} error={error} /&gt;<br> ) : (<br>&lt;yourverifyform<br>onSubmit={handleVerify}<br>onResend={handleResendCode}<br>error={error}<br>email={email}<br>/&gt;<br> )}<br>&lt;/div&gt;)</pre><p>That’s a wrap.<br>You can share how useful this was on the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98aeea966248" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-create-custom-clerk-auth-forms-and-google-authentication-with-nextjs-and-tailwind-98aeea966248">How to Create Custom Clerk Auth Forms and Google authentication with NextJS, and Tailwind</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Safely Store HTML Content as string in any DB and Prevent XSS Attacks in Your DB.]]></title>
            <link>https://medium.com/@vitalismutwiri/how-to-safely-store-html-content-as-string-in-any-db-and-prevent-xss-attacks-in-your-db-2c326e0804ad?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c326e0804ad</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 21:44:30 GMT</pubDate>
            <atom:updated>2024-10-19T21:44:30.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*6HfmjfoFC5NWQE1o" /></figure><p>Hello, folks! 👋 Recently, I embarked on setting up a simple blog infrastructure where I could create my own upload page, store data in a database, and then retrieve and display that data on a webpage. Pretty simple, right? Well, since I wanted to keep things lightweight, I opted for a NoSQL, document-oriented database (which basically stores data as key-value pairs in JSON-like documents).</p><p>But here’s where things got tricky: I was storing the rich-text editor values as HTML strings. If you’re already thinking “Wait, that’s susceptible to XSS (cross-site scripting) attacks,” you’re absolutely right! Storing raw HTML as a string is a <strong>big no-no</strong> when it comes to security. So, what did I do to solve this? Let’s break it down!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*Flc27JkdBdTUqelG.gif" /></figure><h3>🚀 The Solution</h3><p>My solution was to sanitize the HTML content from the rich-text editor. Essentially, I found a way to strip away harmful scripts and unwanted spaces, while allowing the necessary tags and attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zMk9ooCkRQtcbcgg" /></figure><h3>🧩 Step-by-Step Breakdown of the Solution</h3><h4>Step 1: What Does “Sanitize” Mean, Anyway?</h4><p>Great question! 😎 Do you remember the COVID-19 pandemic, when we had to sanitize our hands like a thousand times a day? The whole point was to kill or remove harmful bacteria that could make us sick. Well, sanitizing HTML is kinda the same thing. We’re going to:</p><ol><li><strong>Remove harmful scripts</strong> (like script tags that could execute malicious code).</li><li><strong>Allow tags and attributes that we want</strong> (for example, we’ll keep image tags and allow src and alt attributes).</li><li><strong>Trim spaces</strong> (because who needs extra spaces cluttering things up?).</li></ol><p>And guess what? There’s a handy-dandy npm package called sanitize-html that does all of this for us! 🎉</p><h4>Step 2: Installing the Package</h4><p>To install sanitize-html, just run this command in your project:</p><pre>npm install sanitize-html</pre><h4>Step 3: Writing the Code</h4><p>Now, let’s dive into the code. Here’s a function that sanitizes the rich text content from the editor:</p><pre>import sanitizeHtml from &#39;sanitize-html&#39;;<br><br>export function sanitizeRichTextContent(content) {<br>  return sanitizeHtml(content, {<br>    allowedTags: sanitizeHtml.defaults.allowedTags.concat([&#39;img&#39;]),<br>    allowedAttributes: {<br>      ...sanitizeHtml.defaults.allowedAttributes,<br>      img: [&#39;src&#39;, &#39;alt&#39;],<br>    },<br>    exclusiveFilter: (frame) =&gt; {<br>      return frame.tag === &#39;script&#39;;<br>    },<br>    textFilter: (text) =&gt; {<br>      return text.replace(/\s+/g, &quot; &quot;).trim();<br>    }<br>  });<br>}</pre><h3>📜 What Does This Code Do?</h3><ol><li><strong>Tags</strong>: It allows all default HTML tags like &lt;a&gt;, &lt;p&gt;, &lt;strong&gt;, and &lt;em&gt;. Additionally, it allows the &lt;img&gt; tag, which is not included by default.</li><li><strong>Attributes</strong>: It ensures that allowed tags can only have specific attributes. For example, &lt;img&gt; tags can only have src and alt attributes—no shady JavaScript events like onclick allowed! 🚫</li><li><strong>Text Cleaning</strong>: It removes any extra spaces and trims the content for a nice, clean output.</li><li><strong>No Scripts Allowed!</strong>: The function strictly removes any &lt;script&gt; tags to prevent potential cross-site scripting (XSS) attacks.</li></ol><h3>🛠 Step 4: Using the Sanitizer in Your Backend</h3><p>Now that we have our sanitizer function, we need to use it before storing any data in our database. Here’s an example of how I did it in my code.</p><pre>// File: src/pages/api/upload-blog.js<br><br>import clientPromise from &#39;../../lib/mongodb&#39;;<br>import { createBlogPost, BlogPostSchema } from &#39;../../models/BlogPost&#39;;<br>import { sanitizeRichTextContent } from &#39;../../utils/htmlSanitizer&#39;;<br><br>export async function POST({ request }) {<br>  let blogData = await request.json();<br><br>  try {<br>    // Validate blogData against BlogPostSchema<br>    Object.keys(BlogPostSchema).forEach(key =&gt; {<br>      if (BlogPostSchema[key].required &amp;&amp; !blogData[key]) {<br>        throw new Error(`${key} is required`);<br>      }<br>    });<br><br>    if (blogData) {<br>      blogData = sanitizeRichTextContent(blogData);<br>    }<br><br>    const client = await clientPromise;<br>    const db = client.db(&quot;blogDatabase&quot;);<br>    const collection = db.collection(&quot;posts&quot;);<br><br>    const blogPost = createBlogPost(blogData);<br>    const result = await collection.insertOne(blogPost);<br><br>    return new Response(JSON.stringify({ success: true, id: result.insertedId }), {<br>      status: 200,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>    });<br>  } catch (error) {<br>    return new Response(JSON.stringify({ success: false, error: error.message }), {<br>      status: 500,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>    });<br>  }<br>}</pre><h3>📝 Key Takeaways</h3><ul><li><strong>Sanitize your inputs!</strong> Whether you’re building a simple blog or a full-fledged app, never store raw HTML as a string in your database. Always clean it up first to avoid security risks like XSS attacks.</li><li><strong>Use helpful tools!</strong> The sanitize-html package makes it incredibly easy to filter out harmful content and ensure that only the tags and attributes you want are stored.</li><li><strong>Store HTML as string </strong>By removing the spaces you have one continuous HTML which is taken as a long string.</li></ul><p>That’s a wrap</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c326e0804ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Ruby API-Only App on Render]]></title>
            <link>https://medium.com/@vitalismutwiri/deploying-a-ruby-api-only-app-on-render-2177f787be74?source=rss-266ae7508a8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2177f787be74</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Vitalismutwiri]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 17:48:35 GMT</pubDate>
            <atom:updated>2024-10-11T17:48:35.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-BvwwGwzEP1xqNO" /></figure><p>Ready to bring your Ruby on Rails API into the cloud and make it production-ready? In this guide, we’ll dive into the exciting world of deploying an API-only Rails backend to Render.<br>For free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*99rG8o9KSe5j6krP" /></figure><h4>Step 1: Set Up Your Project</h4><p>First, create a folder for your project and initialize the app.</p><pre>mkdir your_project_folder<br><br>cd your_project_folder<br><br><br></pre><pre><br>##i will call my app quotes api<br><br>rails new quotes_api --api -d postgresql<br><br>--api generates an API-only Rails application.<br>-d postgresql specifies PostgreSQL as the database.<br></pre><h4>Step 2: Set Up the Database</h4><pre>cd your_app<br>cd quotes_api<br><br>code . - to open the visual studio code, if you are using cursor or zed - https://zed.dev/download open from the folder<br></pre><p>If you use another editor like Zed, you can <a href="https://zed.dev/download">download it here</a>.</p><h4>Database Configuration</h4><p>Your config/database.yml file, will look like this without comments.</p><pre><br>default: &amp;default<br>  adapter: postgresql<br>  encoding: unicode<br>  # For details on connection pooling, see Rails configuration guide<br>  # https://guides.rubyonrails.org/configuring.html#database-pooling<br>  pool: &lt;%= ENV.fetch(&quot;RAILS_MAX_THREADS&quot;) { 5 } %&gt;<br><br>development:<br>  &lt;&lt;: *default<br>  database: quotes_api_development<br><br><br>test:<br>  &lt;&lt;: *default<br>  database: quotes_api_test<br><br><br>production:<br>  &lt;&lt;: *default<br>  database: quotes_api_production<br>  username: quotes_api<br>  password: &lt;%= ENV[&quot;QUOTES_API_DATABASE_PASSWORD&quot;] %&gt;</pre><p>If you wish to set-up the development you will need to configure the database by adding the following:<br><br>1. username: your_postgres_username <br>2. password: your_postgres_password <br>3. host: localhost<br>4. Port: Port your database is running on</p><p>If your root user does not exist or lacks permissions, you can follow <a href="https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps-2">digital ocean blog</a> to learn about creating PostgreSQL roles and permissions.</p><h4>Step 3: Create a Model</h4><p>Next we will create a very simple model, learn about <a href="https://guides.rubyonrails.org/active_record_basics.html">creating models here,</a> and use this tool to <a href="https://rails-generate.com/">generate models</a></p><pre>rails g model Quote content:string author:string</pre><p>Then, open db/seeds.rb for me i will add dummy data:</p><pre>Quote.create(content: &quot;The only limit to our realization of tomorrow is our doubts of today.&quot;, author: &quot;Franklin D. Roosevelt&quot;)<br>Quote.create(content: &quot;In the end, we will remember not the words of our enemies, but the silence of our friends.&quot;, author: &quot;Martin Luther King, Jr.&quot;)<br>Quote.create(content: &quot;Success is not final, failure is not fatal: It is the courage to continue that counts.&quot;, author: &quot;Winston Churchill&quot;)</pre><p>Run the seed command: for local environment purposes.</p><pre>rails db:seed</pre><h4>Step 4: Create a Controller</h4><pre>rails g controller api/v1/quotes</pre><p>for my controllers this will be my code</p><p>app/controllers/api/v1/quotes_controller.rb</p><pre>module Api<br>  module V1<br>    class QuotesController &lt; ApplicationController<br>      # all quotes<br>      def index<br>        quotes = Quote.all<br>        render json: quotes<br>      end<br>      # random quotes<br>      def random<br>        quote = Quote.order(&#39;RANDOM()&#39;).first<br>        render json: quote<br>      end<br>    end<br>  end<br>end</pre><h4>Step 5: Define <a href="https://guides.rubyonrails.org/routing.html">Routes</a></h4><p>config/routes.rb</p><pre>Rails.application.routes.draw do<br>  namespace :api do<br>    namespace :v1 do<br>      resources :quotes, only: [:index] do<br>        collection do<br>          get &#39;random&#39;<br>        end<br>      end<br>    end<br>  end<br>end</pre><p>This creates the following endpoints:</p><ul><li>GET /api/v1/quotes – fetches all quotes.</li><li>GET /api/v1/quotes/random – fetches a random quote.</li></ul><h4>Step 6: Prepare for Deployment</h4><p><strong>1. First step</strong><br>Update database.ymlIn the production section of config/database.yml, replace your production database settings with:</p><pre>production:<br>  &lt;&lt;: *default<br>  url: &lt;%= ENV[&#39;DATABASE_URL&#39;] %&gt;</pre><p>This will fetch the database URL from the DATABASE_URL environment variable, which you will set in Render.</p><h4>if you installed the current ruby<br> leave the puma.rb as it is</h4><p><strong>Second Step </strong><br>Update production.rb<br>add this line after line 23</p><pre> config.public_file_server.enabled = ENV[&#39;RAILS_SERVE_STATIC_FILES&#39;].present? || ENV[&#39;RENDER&#39;].present?</pre><pre>require &quot;active_support/core_ext/integer/time&quot;<br><br>Rails.application.configure do<br>  # Settings specified here will take precedence over those in config/application.rb.<br><br>  # Code is not reloaded between requests.<br>  config.enable_reloading = false<br><br>  # Eager load code on boot. This eager loads most of Rails and<br>  # your application in memory, allowing both threaded web servers<br>  # and those relying on copy on write to perform better.<br>  # Rake tasks automatically ignore this option for performance.<br>  config.eager_load = true<br><br>  # Full error reports are disabled and caching is turned on.<br>  config.consider_all_requests_local = false<br><br>  # Ensures that a master key has been made available in ENV[&quot;RAILS_MASTER_KEY&quot;], config/master.key, or an environment<br>  # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files).<br>  # config.require_master_key = true<br><br>  # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead.<br>  # config.public_file_server.enabled = false<br>  config.public_file_server.enabled = ENV[&#39;RAILS_SERVE_STATIC_FILES&#39;].present? || ENV[&#39;RENDER&#39;].present?<br><br>  # Enable serving of images, stylesheets, and JavaScripts from an asset server.<br>  # config.asset_host = &quot;http://assets.example.com&quot;<br><br>  # Specifies the header that your server uses for sending files.<br>  # config.action_dispatch.x_sendfile_header = &quot;X-Sendfile&quot; # for Apache<br>  # config.action_dispatch.x_sendfile_header = &quot;X-Accel-Redirect&quot; # for NGINX<br><br>  # Store uploaded files on the local file system (see config/storage.yml for options).<br>  config.active_storage.service = :local<br><br>  # Mount Action Cable outside main process or domain.<br>  # config.action_cable.mount_path = nil<br>  # config.action_cable.url = &quot;wss://example.com/cable&quot;<br>  # config.action_cable.allowed_request_origins = [ &quot;http://example.com&quot;, /http:\/\/example.*/ ]<br><br>  # Assume all access to the app is happening through a SSL-terminating reverse proxy.<br>  # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies.<br>  # config.assume_ssl = true<br><br>  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.<br>  config.force_ssl = true<br><br>  # Log to STDOUT by default<br>  config.logger = ActiveSupport::Logger.new(STDOUT)<br>    .tap  { |logger| logger.formatter = ::Logger::Formatter.new }<br>    .then { |logger| ActiveSupport::TaggedLogging.new(logger) }<br><br>  # Prepend all log lines with the following tags.<br>  config.log_tags = [ :request_id ]<br><br>  # &quot;info&quot; includes generic and useful information about system operation, but avoids logging too much<br>  # information to avoid inadvertent exposure of personally identifiable information (PII). If you<br>  # want to log everything, set the level to &quot;debug&quot;.<br>  config.log_level = ENV.fetch(&quot;RAILS_LOG_LEVEL&quot;, &quot;info&quot;)<br><br>  # Use a different cache store in production.<br>  # config.cache_store = :mem_cache_store<br><br>  # Use a real queuing backend for Active Job (and separate queues per environment).<br>  # config.active_job.queue_adapter = :resque<br>  # config.active_job.queue_name_prefix = &quot;quotes_api_production&quot;<br><br>  config.action_mailer.perform_caching = false<br><br>  # Ignore bad email addresses and do not raise email delivery errors.<br>  # Set this to true and configure the email server for immediate delivery to raise delivery errors.<br>  # config.action_mailer.raise_delivery_errors = false<br><br>  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to<br>  # the I18n.default_locale when a translation cannot be found).<br>  config.i18n.fallbacks = true<br><br>  # Don&#39;t log any deprecations.<br>  config.active_support.report_deprecations = false<br><br>  # Do not dump schema after migrations.<br>  config.active_record.dump_schema_after_migration = false<br><br>  # Enable DNS rebinding protection and other `Host` header attacks.<br>  # config.hosts = [<br>  #   &quot;example.com&quot;,     # Allow requests from example.com<br>  #   /.*\.example\.com/ # Allow requests from subdomains like `www.example.com`<br>  # ]<br>  # Skip DNS rebinding protection for the default health check endpoint.<br>  # config.host_authorization = { exclude: -&gt;(request) { request.path == &quot;/up&quot; } }<br>end</pre><h3>Create a PostgreSQL database</h3><p>Render allows users to create one PostgreSQL database that lasts 90 days in the free tier. You can always create a new one when the old one expires. The process of creating one goes as follows:</p><ol><li>Login to <a href="https://dashboard.render.com/">render.com</a> or create a new account if you haven’t already. You can use your GitHub account to allow your repositories to be deployed on push.</li><li>In the navbar click on the New button and select the PostgreSQL option:</li><li>Choose a name and a region. You can also customize the database name, user, and version if you need it.</li><li>Choose the Free Plan Type and click on Create Database</li><li>Wait until the newly created database is deployed, then copy its <strong>Internal Database URL</strong> and save it for later.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6TkkAMNdg8X3J8el.png" /></figure><h3>Create a build script</h3><p>The api-only script is different form other scripts here it is.<br>you need to create a file called bin/render-build.sh and paste the following:</p><pre>#!/usr/bin/env bash<br># exit on error<br>set -o errexit<br><br>bundle install<br>bundle exec rake db:migrate<br>bundle exec rake db:seed # optional</pre><p>Next, make sure the script is executable by running the following command in the console:</p><pre>chmod a+x bin/render-build.sh</pre><p>Check your master key it will be found in</p><pre>config/master.key</pre><p>if none not be worried</p><p><strong>Generate Master.key</strong><br> Using:</p><pre>bin/rails credentials:edit</pre><blockquote>Push the changes and you are ready to deploy.</blockquote><h3>Create a Web Service</h3><p>Now you can create a Web Service in Render by clicking on New &gt;&gt; Web Service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9gBZ9iXsZoaWSwb6.png" /></figure><p>In the next window, configure your GitHub account if you haven’t. Then, you can choose the repository you want to deploy. Find it and click on Connect.</p><p>Afterward, you can configure a unique name, the region, and the branch you want to deploy, in case you don’t want to deploy the default GitHub branch.</p><p><strong>Important:</strong></p><p>Ensure that the environment is set to Ruby. Make sure to clear the Build Command and set it to:</p><pre>./bin/render-build.sh</pre><p>Which calls the previously created script. Also, clear the Start Command and set it to:</p><pre>bundle exec puma -C config/puma.rb</pre><p>You should have your configuration as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0yI09S1bql1IONu1.png" /></figure><p>Next, you can check the Plan Type and ensure is set to Free. Then, you should click the Advanced button.</p><p>Now you need to add all the environmental variables your application requires. The two mandatory variables are:</p><pre>DATABASE_URL =&gt; The internal database URL that you saved above form you PostgreSQL service<br>RAILS_MASTER_KEY =&gt; Paste contents of the config/master.key file</pre><figure><img alt="Internal Database Url" src="https://cdn-images-1.medium.com/max/1024/1*LdMKDgI3SBOmHePeSgo5TQ.png" /></figure><p>when getting the database internal url you will find something like the above image.<br>Click on the eye icon to be allowed to copy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*V6CBD_zwvT5xbQkc.png" /></figure><p><strong>Finally, you can click Create Web Service</strong></p><h4>Bugs you might face</h4><h4>1. when you try running model it will inform you that: Your Ruby version is 3.1.4, but your Gemfile specified 3.0.2</h4><p>For deployment use 3.1.4 if you don’t have ruby 3.1.4 install it using <a href="https://github.com/rbenv/rbenv">rbenv</a></p><p>For our problem go to the gemfile and change the version to 3.1.4</p><h4>2. if you face this error<br><strong>==&gt; Only Ruby versions above 3.1.0 are supported, you have requested 3.0.2</strong></h4><p>Access your local shell or command line</p><p>run the following command</p><pre>rbenv install 3.1.4</pre><p>if you have already installed the 3.1.4 version run the following command</p><pre>rbenv local 3.1.4<br># then run <br>bundle install</pre><p>Add your changes then commit and push them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*Fk_xQ3dBoSI2ruRi3Kq-oQ.png" /></figure><p><strong>On your service click </strong><br>clear build cache and deploy / create a new web service</p><h4>Results</h4><p>I am using Thunder Client extension to check my APIs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*45aFJh7G-_tOEijNgWm_1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*r1Wdql-kF1qddlDrtW8bVw.png" /></figure><p>Hope you enjoyed it, comment and follow me on Github.<br>Credits<br>- <a href="https://betterprogramming.pub/how-to-deploy-an-api-only-ruby-on-rails-application-to-render-6012a19ba2cd">David Vera Castillo blog </a>— it helped me but i had to figure out changes that have happened, that why i have included them in this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2177f787be74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>