<?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 Housni BENABID on Medium]]></title>
        <description><![CDATA[Stories by Housni BENABID on Medium]]></description>
        <link>https://medium.com/@hosnyben?source=rss-ea15e594f595------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GmGN9_rRNECJYwwCdfWfhQ.png</url>
            <title>Stories by Housni BENABID on Medium</title>
            <link>https://medium.com/@hosnyben?source=rss-ea15e594f595------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:22:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hosnyben/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[Automate Your Laravel + React + Meilisearch Setup from Scratch]]></title>
            <link>https://medium.com/@hosnyben/automate-your-laravel-react-meilisearch-phpmyadmin-setup-from-scratch-9a9b6968a1e7?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9b6968a1e7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Sat, 10 May 2025 19:49:33 GMT</pubDate>
            <atom:updated>2025-05-10T21:51:10.765Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a Laravel server from scratch can be tedious, especially when you’re managing multiple projects, environments, or clients. As developers, our time is better spent writing application code, not configuring NGINX blocks or restarting services manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yVuiZ0D-q87rXn2gf23BA.jpeg" /></figure><p>In this post, I’ll walk you through how to write a Bash script that:</p><ul><li>Installs and configures <strong>NGINX, PHP, Redis, Composer</strong></li><li>Sets up Laravel apps from <strong>Git repos</strong></li><li>Automates SSL with <strong>Certbot</strong></li><li>Manages workers via <strong>Supervisor</strong></li><li>Supports <strong>Meilisearch</strong> and optional frontends</li></ul><p>But first, lets break down what are Laravel Server requirements. To get a Laravel application running on a Linux VPS, you generally need the following:</p><ul><li><strong>A Linux distribution: </strong>Debian/Ubuntu-based systems are commonly used.</li><li><strong>A web server:</strong> Typically NGINX or Apache (or both for .htaccess compatibility).</li><li><strong>PHP:</strong> Laravel requires PHP 8.1+ as of Laravel 10/11.</li><li><strong>A database server:</strong> MySQL or PostgreSQL.</li><li><strong>Composer:</strong> For managing Laravel’s PHP dependencies.</li><li><strong>Supervisor: </strong>To keep queue workers running.</li><li><strong>Redis:</strong> For cache/session/queue handling.</li><li><strong>Certbot + SSL:</strong> For HTTPS support.</li><li><strong>Firewall rules:</strong> To lock down unnecessary ports.</li><li><strong>Laravel-specific setup:</strong> .env, queues, crons, file permissions, etc.</li></ul><p>You also need to manually configure each site — vhosts, PHP versions, queue workers, SSL certificates — which becomes redundant and error-prone quickly.</p><p>Now we all agree f the necessity of automating this process.</p><h4>🤖 Why Automate with Bash?</h4><p>Repetition breeds inefficiency. Instead of setting up each new VPS manually — typing the same commands over and over — you can automate it with a single Bash script.</p><p><strong>Advantages:</strong></p><ul><li>🚀 Speed up deployment</li><li>🧪 Reduce human errors</li><li>📦 Enforce consistency across environments</li><li>🔐 Apply standardized security (firewalls, SSL, users)</li><li>🔁 Easily integrate into CI/CD pipelines</li></ul><p>After this long introduction, let’s get our hands dirty :)</p><h3>Improve interface of bash script</h3><p>To keep the output clean and focused, we’ll incorporate a spinner to indicate progress instead of flooding the terminal with logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*HGSS4PGon0GlNICcSPF60Q.gif" /></figure><p>Let’s create the spinner effect with a <strong>“Loading”</strong> message first.</p><pre>echo -ne &quot;\033[0;37m[🛠️] Loading...\033[0m&quot;<br><br>bash -c &quot;npm install&quot; &gt;&quot;process.log&quot; 2&gt;&amp;1 &amp;<br><br>local pid=$!<br>local spinstr=&#39;|/-\\&#39;<br>local delay=0.1<br><br>while kill -0 $pid 2&gt;/dev/null; do<br>  local temp=${spinstr#?}<br>  printf &quot;\r\033[0;37m[🛠️] Loading... [%c]\033[0m&quot; &quot;$spinstr&quot;<br>  local spinstr=$temp${spinstr%&quot;$temp&quot;}<br>  sleep $delay<br>done</pre><p>To silently track background tasks and catch failures, we’re using bash -c “npm install” &gt; process.log 2&gt;&amp;1 &amp;.</p><p>This logs output without cluttering the terminal. Once the process completes, we can highlight the status with color. If it fails, we’ll dump the contents of process.log for quick debugging:</p><pre>wait $pid<br>local status=$?<br><br>if [ $status -eq 0 ]; then<br>  printf &quot;\r\033[0;32m[✅] $msg... Done\033[0m\n&quot;<br>else<br>  printf &quot;\r\033[0;31m[❌] $msg failed\033[0m\n&quot;<br>  echo -e &quot;\033[0;33m🔍 Error output:\033[0m&quot;<br>  cat &quot;process.log&quot;<br>fi</pre><p>And maybe we remove the log file once it’s done:</p><pre>rm &quot;process.log&quot;</pre><p>Now that we’ve gone through the steps to create a spinner effect, it’s time to wrap everything into a reusable function. We’ll define a spinner() function that takes three parameters: the command to run, a title to display while it runs, and the path to the log file.</p><pre>spinner() {<br>  local msg=&quot;$1&quot;<br>  shift<br>  local cmd=&quot;$@&quot;<br>  local log_file=$(mktemp)<br><br>  echo -ne &quot;\033[0;37m[🛠️] $msg...\033[0m&quot;<br><br>  bash -c &quot;$cmd&quot; &gt;&quot;$log_file&quot; 2&gt;&amp;1 &amp;<br>  local pid=$!<br>  local spinstr=&#39;|/-\\&#39;<br>  local delay=0.1<br><br>  while kill -0 $pid 2&gt;/dev/null; do<br>    local temp=${spinstr#?}<br>    printf &quot;\r\033[0;37m[🛠️] $msg... [%c]\033[0m&quot; &quot;$spinstr&quot;<br>    local spinstr=$temp${spinstr%&quot;$temp&quot;}<br>    sleep $delay<br>  done<br><br>  wait $pid<br>  local status=$?<br><br>  if [ $status -eq 0 ]; then<br>    printf &quot;\r\033[0;32m[✅] $msg... Done\033[0m\n&quot;<br>  else<br>    printf &quot;\r\033[0;31m[❌] $msg failed\033[0m\n&quot;<br>    echo -e &quot;\033[0;33m🔍 Error output:\033[0m&quot;<br>    cat &quot;$log_file&quot;<br>  fi<br><br>  rm &quot;$log_file&quot;<br>  return $status<br>}<br><br># Print function in case no loader needed<br>print_status() {<br>  echo -ne &quot;\033[0;37m[working] $1...\033[0m&quot;<br>}<br><br># Print function in case no loader needed<br>print_done() {<br>  echo -ne &quot;\033[0;2K\r\033[0;37m[working] $1... \033[0;32m[done]\033[0m\n&quot;<br>}</pre><p>This way, we can call :</p><pre>spinner &quot;npm install&quot; &quot;Installing dependencies&quot; &quot;process.log&quot;</pre><p>anywhere in our script and keep things clean, consistent, and easy to debug.</p><h3>Set up server requirements</h3><p>Before provisioning Laravel, React, or any service-specific dependencies, we need to bootstrap the server itself.</p><p>This means preparing a lean, production-grade environment — starting with the essentials that turn a bare VPS into a functioning web server.</p><p><strong>First things first:</strong> ensure the script is being executed by the root user — otherwise, fail fast and avoid permission hell later.</p><pre>if [ &quot;$EUID&quot; -ne 0 ]; then<br>  echo -e &quot;\033[1;31m❌ You need root access. Please run this script as root (e.g., with sudo)\033[0m&quot;<br>  exit 1<br>fi</pre><h4>Prompting the PHP Version — with Validation</h4><p>Laravel requires a specific PHP version, and different projects may rely on different minor versions — so hardcoding it isn’t an option. Instead, the script prompts the user to input their desired PHP version.</p><p>But we don’t just accept any input. Before proceeding, we enforce three checks:</p><ul><li>The version must follow a valid format, like 8.2</li><li>It must be PHP 8.0 or higher, as Laravel no longer supports anything below that</li><li>The version must actually exist in the system’s package manager</li></ul><p>To make this possible, the script adds a reliable PHP repository <a href="https://launchpad.net/~ondrej/+archive/ubuntu/php">(Ondřej Surý’s PPA)</a>, ensuring access to all supported versions. This lets us validate the input against what’s installable, not just what the user typed.</p><p>Only once these checks pass do we continue with installing PHP and its required extensions.</p><pre>spinner &quot;Adding PHP repository&quot; add-apt-repository ppa:ondrej/php -y</pre><p>Finally we’ll get this :</p><pre>spinner &quot;Adding PHP repository&quot; add-apt-repository ppa:ondrej/php -y<br>spinner &quot;Updating package lists&quot; apt update<br>spinner &quot;Installing core utils (bc)&quot; apt install -y bc<br><br>while true; do<br>  read -p $&#39;\033[0;32mEnter desired PHP version (e.g., 8.2): \033[0m &#39; php_version<br><br>  if [[ ! &quot;$php_version&quot; =~ ^8\.[0-9]+$ ]]; then<br>    echo &quot;❌ Invalid format. Use format like 8.2&quot;<br>    continue<br>  fi<br><br>  if (( $(echo &quot;$php_version &lt; 8.0&quot; | bc -l) )); then<br>    echo &quot;❌ PHP version must be 8.0 or higher.&quot;<br>    continue<br>  fi<br><br>  if ! apt-cache show php$php_version &amp;&gt;/dev/null; then<br>    echo &quot;❌ PHP $php_version not available in apt. Try another version.&quot;<br>    continue<br>  fi<br><br>  break<br>done</pre><h4>Conditional SSL Validation with Certbot</h4><p>Before issuing an SSL certificate with <a href="https://certbot.eff.org/"><strong>Certbot</strong></a>, we need to verify that the domain actually resolves to the current server. If the DNS isn’t properly configured yet, the validation will fail — and so will the script.</p><p>To avoid unnecessary errors, we first check whether the domain points to the server’s IP. If it doesn’t, we skip the SSL step and mark it for a future pass, once DNS propagation is complete. This ensures the script remains resilient and doesn’t block the rest of the setup on premature SSL attempts.</p><pre>server_ip=$(curl -s https://api.ipify.org)<br>echo &quot;⚠️  BEFORE YOU CONTINUE:&quot;<br>echo -e &quot;\033[0;37mMake sure your domain/subdomain DNS is pointing to this server&#39;s IP:\033[0m\n&quot;<br>echo -e &quot;\033[0;37m ➤ Public IP: $server_ip\033[0m&quot;<br>echo -e &quot;\033[0;37m (check propagation: https://dnschecker.org)\033[0m&quot;<br><br><br>read -p $&#39;\033[0;32mDo you want to skip SSL (Certbot)? (y/n): \033[0m &#39; skip_ssl</pre><h4>Isolating Apps with Dedicated Users</h4><p>For better <strong>security and process isolation</strong>, it’s often a good practice to run each app under its own Linux user. This limits the blast radius of any potential breach and prevents one site from affecting another.</p><p>To support this, the script should prompts for a <strong>username</strong> and ensures that ownership and permissions (<strong>CHOWN</strong> and <strong>CHMOD</strong>) are applied correctly to the app’s directory structure.</p><p>And to make it more intuitive, let’s prompt the username:</p><pre>read -p $&#39;\033[0;32mEnter new deployment username: \033[0m &#39; app_user</pre><p>Once we have the desired username, the next step is to create the user account — but with restricted access. This user will be dedicated to the app and accessible exclusively via SSH.</p><p><strong><em>No shell login, no sudo privileges, and certainly no exposure to anything beyond its own home and project directory.</em></strong></p><pre># Create the user and its folder in /home folder<br>useradd -m -s /bin/bash $app_user<br><br># Locks the user’s password. Disables password-based login for this user.<br>passwd -l $app_user<br><br># Prevents any login that might still be allowed by the system, even after the password is locked.<br>usermod -L $app_user</pre><p>The user can now only access the server via SSH. So we generate an SSH key pair and log in using it — no passwords allowed.</p><pre># Create .ssh folder<br>mkdir -p /home/$app_user/.ssh<br><br># Create ssh key for that user<br>sudo -u $app_user ssh-keygen -t rsa -b 4096 -f /tmp/id_rsa -N &quot;&quot;<br>mv /tmp/id_rsa /home/$app_user/.ssh/id_rsa<br>mv /tmp/id_rsa.pub /home/$app_user/.ssh/id_rsa.pub<br><br># Mark the ssh key autorized<br>cat /home/$app_user/.ssh/id_rsa.pub &gt; /home/$app_user/.ssh/authorized_keys<br><br># Set the proper CHMOD properties<br>chmod 700 /home/$app_user/.ssh<br>chmod 600 /home/$app_user/.ssh/authorized_keys<br>chown -R $app_user:$app_user /home/$app_user/.ssh<br>chmod o+x /home/$app_user</pre><p>Now our script can:</p><ol><li>Prompt for a <strong>username</strong></li><li>Create an SSH-only user</li><li>Generate an SSH key for access</li></ol><p><strong><em>But what if we run it again later to add another app under the same user?</em></strong><br>We shouldn’t touch an existing user. Instead, we first check if the user already exists — and if so, we simply display their public SSH key, ready to be reused (e.g., for Git access).</p><pre>read -p $&#39;\033[0;32mEnter new deployment username: \033[0m &#39; app_user<br><br>if id -u &quot;$app_user&quot; &gt;/dev/null 2&gt;&amp;1; then<br>  echo &quot;User $app_user already exists. Skipping creation and SSH key generation.&quot;<br>else<br>  useradd -m -s /bin/bash $app_user<br>  passwd -l $app_user<br>  usermod -L $app_user<br><br>  mkdir -p /home/$app_user/.ssh<br>  sudo -u $app_user ssh-keygen -t rsa -b 4096 -f /tmp/id_rsa -N &quot;&quot;<br>  mv /tmp/id_rsa /home/$app_user/.ssh/id_rsa<br>  mv /tmp/id_rsa.pub /home/$app_user/.ssh/id_rsa.pub<br>  cat /home/$app_user/.ssh/id_rsa.pub &gt; /home/$app_user/.ssh/authorized_keys<br>  chmod 700 /home/$app_user/.ssh<br>  chmod 600 /home/$app_user/.ssh/authorized_keys<br>  chown -R $app_user:$app_user /home/$app_user/.ssh<br>  chmod o+x /home/$app_user<br>fi<br><br>echo -e &quot;\033[0;37m🔑 Add this SSH public key to your Git repositories:\033[0m&quot;<br>cat /home/$app_user/.ssh/id_rsa.pub<br><br>echo -e &quot;\033[0;37m⏳ Press ENTER when you&#39;re done copying to continue...\033[0m&quot;</pre><h4>Logging Important Credentials</h4><p>After installation, we need to safely store essential credentials (e.g., database passwords) for future reference. We’ll do this by generating a summary file, secured with permissions so that only the app user can access it:</p><pre>SUMMARY_FILE=&quot;/home/$app_user/server-setup-summary.txt&quot;<br>touch $SUMMARY_FILE<br>chown $app_user:$app_user $SUMMARY_FILE<br>chmod 600 $SUMMARY_FILE</pre><h4>Install Required System Packages</h4><p>Next, we install only the essential packages necessary to set up a fully operational web server environment:</p><pre>spinner &quot;Install system packages&quot; apt install -y nginx git curl unzip ufw nodejs npm build-essential autoconf pkg-config zlib1g-dev certbot python3-certbot-nginx fzf</pre><h3>Configuring Firewall Rules for Security (Security measure)</h3><p>To secure the server, we strictly limit inbound and outbound connections. Earlier, we installed <strong>ufw</strong>, a simple firewall utility, precisely for this purpose.</p><p>Now, let’s open only the essential ports:</p><ul><li>Port: <strong>80/tcp</strong></li><li>Port: <strong>443/tcp</strong></li></ul><p>Wondering why port 80? We’ll explain soon enough — stay tuned. 😅</p><p>We’ll explicitly limit these ports to <strong>HTTP</strong> traffic by adding the /tcp protocol flag — ensuring connections are allowed only over TCP.</p><pre>spinner &quot;Setting up UFW&quot; ufw allow OpenSSH &amp;&amp; ufw allow 80/tcp &amp;&amp; ufw --force enable</pre><p>OpenSSH refers to 443 so we’re good.</p><p>UFW won’t function correctly within <strong>Docker containers</strong>. To avoid issues, we first detect if we’re running inside Docker — if so, we skip configuring UFW.</p><pre># Detect if running inside Docker<br>if grep -q docker /proc/1/cgroup; then<br>  echo -e &quot;\033[0;33m⚠️ Skipping UFW setup inside Docker container\033[0m&quot;<br>else<br>  spinner &quot;Setting up UFW&quot; ufw allow OpenSSH &amp;&amp; ufw allow 80/tcp &amp;&amp; ufw --force enable<br>fi</pre><h3>Application Setup Wizard</h3><p>Now, let’s build an intuitive script that prompts us for key details:</p><ul><li>Application type <em>(Laravel, React or Meilisearch)</em></li><li>Domain name</li><li>And the port where you want the app to be accessed with <em>(Default : 443)</em></li></ul><pre>echo -e &quot;\n\033[0;37m📦 Setting up the app\033[0m&quot;<br>read -p $&#39;\033[0;32mEnter domain (e.g., app.example.com): \033[0m &#39; domain<br><br>read -p $&#39;\033[0;32mEnter app port (or leave blank for HTTPS-only): \033[0m &#39; port<br><br># Accept only Laravel, React or Meilisearch<br>app_type=$(printf &quot;laravel\nreact\nmeilisearch&quot; | fzf --prompt=&quot;Choose app type: &quot; --height=10 --reverse)<br><br>if [[ -z &quot;$app_type&quot; ]]; then<br>  echo &quot;❌ No app type selected. Exiting.&quot;<br>  exit 1<br>fi</pre><p>Next, the script verifies if your chosen port is already in use. If it is, you’ll see the domain name of the app currently using it, and you’ll be prompted to confirm if you still want to proceed. <strong>Don’t worry — NGINX configurations can handle multiple apps on the same port seamlessly (more on that later 😎).</strong></p><p>Additionally, we perform a quick check to ensure you’re not unintentionally setting up the same application twice, with the same domain and port combination, preventing any unwanted surprises down the line.</p><pre>if [[ -n &quot;$port&quot; ]]; then<br>  if lsof -i :$port &amp;&gt;/dev/null; then<br>    echo -e &quot;\033[0;33m⚠️  Port $port is already in use.\033[0m&quot;<br>    existing_sites=$(grep -lr &quot;listen $port&quot; /etc/nginx/sites-available 2&gt;/dev/null | xargs -r grep -E &quot;server_name&quot; | awk &#39;{print $2}&#39; | tr -d &#39;;&#39;)<br>    if [[ -n &quot;$existing_sites&quot; ]]; then<br>      echo -e &quot;\033[0;33m🔍 Detected this port is already used by domain(s):\033[0m $existing_sites&quot;<br>      read -p $&#39;\033[0;32mAre you sure you want to continue using this port? (y/n): \033[0m &#39; continue_port<br>      if [[ &quot;$continue_port&quot; != &quot;y&quot; ]]; then<br>        echo &quot;Aborting due to port conflict.&quot;<br>        exit 1<br>      fi<br>    else<br>      echo -e &quot;\033[0;33mNo matching domain found for this port in NGINX, but it is in use.\033[0m&quot;<br>      read -p $&#39;\033[0;32mContinue anyway? (y/n): \033[0m &#39; continue_anyway<br>      if [[ &quot;$continue_anyway&quot; != &quot;y&quot; ]]; then<br>        echo &quot;Aborting due to port conflict.&quot;<br>        exit 1<br>      fi<br>    fi<br>  fi<br>fi</pre><p>If no port mentioned we use the default one :</p><pre>if [[ -z &quot;$port&quot; ]]; then<br>  port=443<br>fi</pre><p>Now let’s define the application path as we’re going to use it numerous times, the path will be the user path / app domain name :</p><pre>app_path=&quot;/home/$app_user/$domain&quot;</pre><h4>Clone application repository :</h4><p>The only application that requires your source code is <strong>Laravel</strong> and <strong>React. </strong>So we’ll check the application type and clone its repository :</p><pre>if [[ &quot;$app_type&quot; == &quot;laravel&quot; || &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>  read -p $&#39;\033[0;32mEnter Git repo URL: \033[0m &#39; repo_url<br>  clone_git_repo &quot;$repo_url&quot; &quot;$app_user&quot; &quot;$app_path&quot;<br>fi</pre><p><strong>⚠️ IMPORTANT:</strong> Do not forget to add the ssh key we generated above in your git repository before getting to this step.</p><h4>Prepare installation per application type</h4><p>For each application we may need to answer some question :</p><ul><li><strong>Laravel: </strong><br>- How many Mysql databases?<br>- Looking to user <strong>supervisor</strong> for queued jobs? How many workers, what’s the queue name you’ll looking to use?</li><li><strong>Meilisearch:</strong><br>- What internal port you want to use to run it.</li></ul><p>Let’s start with <strong>Laravel. </strong>We may want to have a loop to create as much of databases we want:</p><pre>read -p $&#39;\033[0;32mAdd a database for this app? (y/n): \033[0m &#39; add_db<br><br>if [[ &quot;$add_db&quot; == &quot;y&quot; ]]; then<br>    while true; do<br>        read -p $&#39;\033[0;32mEnter DB name: \033[0m &#39; db_name<br>        db_names+=&quot;$db_name &quot;<br>        read -p $&#39;\033[0;32mAdd another DB? (y/n): \033[0m &#39; another_db<br>        [[ &quot;$another_db&quot; != &quot;y&quot; ]] &amp;&amp; break<br>    done<br>fi</pre><p>Now we have list of all databases we need. Let’s answer our questions about <strong>supervisor</strong>.</p><pre>read -p $&#39;\033[0;32mUse Supervisor for Laravel queue workers? (y/n): \033[0m &#39; use_sup<br>if [[ &quot;$use_sup&quot; == &quot;y&quot; ]]; then<br>    read -p $&#39;\033[0;32mNumber of workers: \033[0m &#39; worker_count<br>    read -p $&#39;\033[0;32mQueue names (comma/default): \033[0m &#39; worker_queues<br>else<br>    worker_count=0<br>    worker_queues=&quot;&quot;<br>fi</pre><p>For Meilisearch, it’s easy, just a prompt of internal port, use <strong>7700</strong> by default :</p><pre>read -p $&#39;\033[0;32mEnter meilisearch internal port (Default 7700): \033[0m &#39; msport<br>[[ -z &quot;$msport&quot; ]] &amp;&amp; msport=7700</pre><h4>Application installation in loop</h4><p>Ideally, wrap the setup logic within a loop, allowing you to quickly create and configure as many apps as you like.</p><pre>app_index=1<br><br>while true; do<br>  echo -e &quot;\n\033[0;37m📦 Setting up app #$app_index\033[0m&quot;<br>  read -p $&#39;\033[0;32mEnter domain (e.g., app.example.com): \033[0m &#39; domain<br><br>  # Application installation per type<br><br>  read -p $&#39;\033[0;32mAdd another app? (y/n): \033[0m &#39; add_more<br>  [[ &quot;$add_more&quot; != &quot;y&quot; ]] &amp;&amp; break<br>  ((app_index++))<br>done</pre><p>We need also to make sure we setup nginx for each app after being installed.</p><p>Which will give us ths final results :</p><pre>app_index=1<br><br>while true; do<br>  echo -e &quot;\n\033[0;37m📦 Setting up app #$app_index\033[0m&quot;<br>  read -p $&#39;\033[0;32mEnter domain (e.g., app.example.com): \033[0m &#39; domain<br><br>  read -p $&#39;\033[0;32mEnter app port (or leave blank for HTTPS-only): \033[0m &#39; port<br><br>  app_type=$(printf &quot;laravel\nreact\nmeilisearch&quot; | fzf --prompt=&quot;Choose app type: &quot; --height=10 --reverse)<br><br>  if [[ -z &quot;$app_type&quot; ]]; then<br>    echo &quot;❌ No app type selected. Exiting.&quot;<br>    exit 1<br>  fi<br><br>  if [[ -n &quot;$port&quot; ]]; then<br>    if lsof -i :$port &amp;&gt;/dev/null; then<br>      echo -e &quot;\033[0;33m⚠️  Port $port is already in use.\033[0m&quot;<br>      existing_sites=$(grep -lr &quot;listen $port&quot; /etc/nginx/sites-available 2&gt;/dev/null | xargs -r grep -E &quot;server_name&quot; | awk &#39;{print $2}&#39; | tr -d &#39;;&#39;)<br>      if [[ -n &quot;$existing_sites&quot; ]]; then<br>        echo -e &quot;\033[0;33m🔍 Detected this port is already used by domain(s):\033[0m $existing_sites&quot;<br>        read -p $&#39;\033[0;32mAre you sure you want to continue using this port? (y/n): \033[0m &#39; continue_port<br>        if [[ &quot;$continue_port&quot; != &quot;y&quot; ]]; then<br>          echo &quot;Aborting due to port conflict.&quot;<br>          exit 1<br>        fi<br>      else<br>        echo -e &quot;\033[0;33mNo matching domain found for this port in NGINX, but it is in use.\033[0m&quot;<br>        read -p $&#39;\033[0;32mContinue anyway? (y/n): \033[0m &#39; continue_anyway<br>        if [[ &quot;$continue_anyway&quot; != &quot;y&quot; ]]; then<br>          echo &quot;Aborting due to port conflict.&quot;<br>          exit 1<br>        fi<br>      fi<br>    fi<br>  fi<br><br>  if [[ -z &quot;$port&quot; ]]; then<br>    port=443<br>  fi<br>  <br>  app_path=&quot;/home/$app_user/$domain&quot;<br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; || &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    read -p $&#39;\033[0;32mEnter Git repo URL: \033[0m &#39; repo_url<br>    clone_git_repo &quot;$repo_url&quot; &quot;$app_user&quot; &quot;$app_path&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>    read -p $&#39;\033[0;32mInstall gRPC extension? (y/n): \033[0m &#39; install_grpc<br>    read -p $&#39;\033[0;32mDo you want to import a MySQL dump file? (y/n): \033[0m &#39; import_dump<br><br>    db_names=&quot;&quot;<br>    if [[ &quot;$import_dump&quot; == &quot;y&quot; ]]; then<br>        read -p $&#39;\033[0;32mEnter path to .zip or .7z dump file: \033[0m &#39; dump_path<br>        add_db=&quot;n&quot;<br>    else<br>        dump_path=&quot;&quot;<br>        read -p $&#39;\033[0;32mAdd a database for this app? (y/n): \033[0m &#39; add_db<br><br>        if [[ &quot;$add_db&quot; == &quot;y&quot; ]]; then<br>            while true; do<br>                read -p $&#39;\033[0;32mEnter DB name: \033[0m &#39; db_name<br>                db_names+=&quot;$db_name &quot;<br>                read -p $&#39;\033[0;32mAdd another DB? (y/n): \033[0m &#39; another_db<br>                [[ &quot;$another_db&quot; != &quot;y&quot; ]] &amp;&amp; break<br>            done<br>        fi<br>    fi<br><br>    read -p $&#39;\033[0;32mUse Supervisor for Laravel queue workers? (y/n): \033[0m &#39; use_sup<br>    if [[ &quot;$use_sup&quot; == &quot;y&quot; ]]; then<br>        read -p $&#39;\033[0;32mNumber of workers: \033[0m &#39; worker_count<br>        read -p $&#39;\033[0;32mQueue names (comma/default): \033[0m &#39; worker_queues<br>    else<br>        worker_count=0<br>        worker_queues=&quot;&quot;<br>    fi<br><br>    # Laravel set up application process...<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    # React set up application process...<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>    read -p $&#39;\033[0;32mEnter meilisearch internal port (Default 7700): \033[0m &#39; msport<br>    [[ -z &quot;$msport&quot; ]] &amp;&amp; msport=7700<br>    # Meilisearch set up application process...<br>  fi<br><br>  read -p $&#39;\033[0;32mAdd another app? (y/n): \033[0m &#39; add_more<br>  [[ &quot;$add_more&quot; != &quot;y&quot; ]] &amp;&amp; break<br>  ((app_index++))<br>done</pre><h3>Application setup process</h3><p>Now after we made sure we have the wizard ready we may need to create functions for each app type and proceed.</p><h4>Laravel</h4><p>Let’s create a function called setup_laravel_app accepting as parameters all prompts from the above wizard:</p><pre>setup_laravel_app() {<br>  local app_path=&quot;$1&quot;<br>  local php_version=&quot;$2&quot;<br>  local app_user=&quot;$3&quot;<br>  local domain=&quot;$4&quot;<br>  local summary_file=&quot;$5&quot;<br>  local add_db=&quot;$9&quot;<br>  local db_names=&quot;${10}&quot;<br>  local use_sup=&quot;${11}&quot;<br>  local worker_count=&quot;${12}&quot;<br>  local worker_queues=&quot;${13}&quot;<br><br>  # Magic<br>}</pre><p>Let’s install redis-server and the other <strong>php</strong> dependencies:</p><pre># Install Redis server if not already installed<br>if ! command -v redis-server &amp;&gt; /dev/null; then<br>  spinner &quot;Installing Redis server...&quot; apt install -y redis-server &amp;&amp; systemctl enable redis-server &amp;&amp; systemctl start redis-server<br>else<br>  echo -e &quot;\033[0;33m⚠️  Redis server is already installed.\033[0m&quot;<br>fi<br><br># Install Laravel PHP dependencies<br>spinner &quot;Installing Laravel PHP dependencies&quot; apt install -y \<br>  php-xml \<br>  php$php_version \<br>  php$php_version-{fpm,mysql,cli,mbstring,xml,curl,bcmath,zip,gd,common,intl,readline,soap,xdebug,igbinary,redis} \<br>  mysql-server \<br>  supervisor \<br>  composer \<br>  zlib1g-dev</pre><p>We enable redis in php just in case it wasn’t enabled by default and we restart php-fpm</p><pre># Enable extensions just in case<br>phpenmod igbinary redis<br><br># Restart PHP FPM service<br>systemctl restart php$php_version-fpm</pre><p>Now, let’s install composer dependencies and create .env file from the .env.production then laravel generate application key :</p><pre>spinner &quot;Installing Composer dependencies&quot; sudo -u &quot;$app_user&quot; php$php_version /usr/bin/composer install<br>spinner &quot;Set ENV and generate key&quot; cp .env.production .env &amp;&amp; php artisan key:generate</pre><p>Now let’s create a Mysql user, we will generate a<strong> secured password and log it in our summary file</strong>.</p><pre>  db_pass=$(openssl rand -base64 18)<br>  echo -e &quot;[$domain] Laravel App&quot; &gt;&gt; &quot;$summary_file&quot;<br>  echo -e &quot;MySQL User: $app_user&quot; &gt;&gt; &quot;$summary_file&quot;<br>  echo -e &quot;MySQL Password: $db_pass&quot; &gt;&gt; &quot;$summary_file&quot;<br>  mysql -e &quot;CREATE USER IF NOT EXISTS &#39;$app_user&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;$db_pass&#39;;&quot;<br>  mysql -e &quot;CREATE USER IF NOT EXISTS &#39;$app_user&#39;@&#39;127.0.0.1&#39; IDENTIFIED BY &#39;$db_pass&#39;;&quot;<br>  mysql -e &quot;FLUSH PRIVILEGES;&quot;</pre><p>You may notice that I enable connection with this user only through localhost and 127.0.0.1 and not wildcard %. For one reason is to <strong>allow connection only through SSH</strong>.</p><p>You may ask, why localhost and 127.0.0.1 as long it’s similar? In fact, it’s not. localhost will allow connection from the server it self using <strong>mysql-cli</strong>. However 127.0.0.1 will allow you log remotely through ssh using a mysql client such <a href="https://www.mysql.com/products/workbench/"><strong>Mysql Workbench</strong></a> or <a href="https://tableplus.com/"><strong>Table Plus</strong></a>.</p><p>Now we create all databases we specified before and grant to the above user full privileges.</p><pre>if [[ &quot;$add_db&quot; == &quot;y&quot; &amp;&amp; -n &quot;$db_names&quot; ]]; then<br>  for db_name in $db_names; do<br>    mysql -e &quot;CREATE DATABASE IF NOT EXISTS \\\`$db_name\\\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;&quot;<br>    mysql -e &quot;GRANT ALL PRIVILEGES ON \\\`$db_name\\\`.* TO &#39;$app_user&#39;@&#39;localhost&#39;;&quot;<br>    mysql -e &quot;GRANT ALL PRIVILEGES ON \\\`$db_name\\\`.* TO &#39;$app_user&#39;@&#39;127.0.0.1&#39;;&quot;<br>    echo -e &quot;Created DB: $db_name&quot; &gt;&gt; &quot;$summary_file&quot;<br>  done<br>fi</pre><p>Last step, is to create our supervisor worker. We need to create the configuration file and launch <strong>supervisor</strong>:</p><pre>if [[ &quot;$use_sup&quot; == &quot;y&quot; &amp;&amp; &quot;$worker_count&quot; -gt 0 ]]; then<br>    cat &gt; /etc/supervisor/conf.d/${domain}.conf &lt;&lt;EOL<br>[program:${domain}]<br>command=php artisan queue:work --queue=${worker_queues}<br>directory=$app_path<br>autostart=true<br>autorestart=true<br>numprocs=$worker_count<br>stdout_logfile=/var/log/${domain}.log<br>stderr_logfile=/var/log/${domain}.err.log<br>EOL<br><br>  supervisorctl reread<br>  supervisorctl update<br>fi</pre><p>And voila! We have now a ready-to use <strong>Laravel </strong>application. 🎉 The final function should look like this :</p><pre>setup_laravel_app() {<br>  local app_path=&quot;$1&quot;<br>  local php_version=&quot;$2&quot;<br>  local app_user=&quot;$3&quot;<br>  local domain=&quot;$4&quot;<br>  local summary_file=&quot;$5&quot;<br>  local add_db=&quot;$6&quot;<br>  local db_names=&quot;${7}&quot;<br>  local use_sup=&quot;${8}&quot;<br>  local worker_count=&quot;${9}&quot;<br>  local worker_queues=&quot;${10}&quot;<br><br>  cd &quot;$app_path&quot;<br><br>  # Install Redis server if not already installed<br>  if ! command -v redis-server &amp;&gt; /dev/null; then<br>    spinner &quot;Installing Redis server...&quot; apt install -y redis-server &amp;&amp; systemctl enable redis-server &amp;&amp; systemctl start redis-server<br>  else<br>    echo -e &quot;\033[0;33m⚠️  Redis server is already installed.\033[0m&quot;<br>  fi<br><br>  # Install Laravel PHP dependencies<br>  spinner &quot;Installing Laravel PHP dependencies&quot; apt install -y \<br>    php-xml \<br>    php$php_version \<br>    php$php_version-{fpm,mysql,cli,mbstring,xml,curl,bcmath,zip,gd,common,intl,readline,soap,xdebug,igbinary,redis} \<br>    mysql-server \<br>    supervisor \<br>    composer \<br>    zlib1g-dev<br><br>  # Enable extensions just in case<br>  phpenmod igbinary redis<br><br>  # Restart PHP FPM service<br>  systemctl restart php$php_version-fpm<br><br>  spinner &quot;Installing Composer dependencies&quot; sudo -u &quot;$app_user&quot; php$php_version /usr/bin/composer install<br>  spinner &quot;Set ENV and generate key&quot; cp .env.production .env &amp;&amp; php artisan key:generate<br><br>  spinner &quot;Set correct file permissions&quot; sudo chown -R &quot;$app_user&quot;:www-data . &amp;&amp; find . -type f -exec chmod 644 {} \; &amp;&amp; find . -type d -exec chmod 755 {} \; &amp;&amp; sudo chown -R www-data:www-data storage bootstrap/cache &amp;&amp; sudo chmod -R 775 storage bootstrap/cache<br><br>  db_pass=$(openssl rand -base64 18)<br>  echo -e &quot;[$domain] Laravel App&quot; &gt;&gt; &quot;$summary_file&quot;<br>  echo -e &quot;MySQL User: $app_user&quot; &gt;&gt; &quot;$summary_file&quot;<br>  echo -e &quot;MySQL Password: $db_pass&quot; &gt;&gt; &quot;$summary_file&quot;<br>  mysql -e &quot;CREATE USER IF NOT EXISTS &#39;$app_user&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;$db_pass&#39;;&quot;<br>  mysql -e &quot;CREATE USER IF NOT EXISTS &#39;$app_user&#39;@&#39;127.0.0.1&#39; IDENTIFIED BY &#39;$db_pass&#39;;&quot;<br>  mysql -e &quot;FLUSH PRIVILEGES;&quot;<br><br>  if [[ &quot;$add_db&quot; == &quot;y&quot; &amp;&amp; -n &quot;$db_names&quot; ]]; then<br>    for db_name in $db_names; do<br>      mysql -e &quot;CREATE DATABASE IF NOT EXISTS \\\`$db_name\\\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;&quot;<br>      mysql -e &quot;GRANT ALL PRIVILEGES ON \\\`$db_name\\\`.* TO &#39;$app_user&#39;@&#39;localhost&#39;;&quot;<br>      mysql -e &quot;GRANT ALL PRIVILEGES ON \\\`$db_name\\\`.* TO &#39;$app_user&#39;@&#39;127.0.0.1&#39;;&quot;<br>      echo -e &quot;Created DB: $db_name&quot; &gt;&gt; &quot;$summary_file&quot;<br>    done<br>  fi<br><br>  if [[ &quot;$use_sup&quot; == &quot;y&quot; &amp;&amp; &quot;$worker_count&quot; -gt 0 ]]; then<br>      cat &gt; /etc/supervisor/conf.d/${domain}.conf &lt;&lt;EOL<br>[program:${domain}]<br>command=php artisan queue:work --queue=${worker_queues}<br>directory=$app_path<br>autostart=true<br>autorestart=true<br>numprocs=$worker_count<br>stdout_logfile=/var/log/${domain}.log<br>stderr_logfile=/var/log/${domain}.err.log<br>EOL<br><br>    supervisorctl reread<br>    supervisorctl update<br>  fi<br>}</pre><h4>React</h4><p>We need first to install <strong>Node.js</strong> and <strong>npm </strong>:</p><pre>spinner &quot;Installing Node.js and npm&quot; &quot;apt install -y nodejs npm &amp;&amp; npm install -g serve&quot;</pre><p>For the React application the process is much easier. We just need to install npm dependencies and Build the app. The function setup_react_app we look like this :</p><pre>setup_react_app() {<br>    local app_user=&quot;$1&quot;<br>    local app_path=&quot;$2&quot;<br>    <br>    spinner &quot;Installing Node.js and npm&quot; &quot;apt install -y nodejs npm &amp;&amp; npm install -g serve&quot;<br>    <br>    cd &quot;$app_path&quot;<br>    spinner &quot;Installing React dependencies&quot; &quot;sudo -u $app_user npm install&quot;<br>    spinner &quot;Building React app&quot; &quot;sudo -u $app_user npm run build&quot;<br>}</pre><p>Now we have our React app builded 🎉</p><h4>Meilisearch</h4><p>I kept the <strong>Meilisearch</strong> for the last part as it’s a bit tricky. As you know, <strong>Meilisearch</strong> must be be always launched in the server and we need to make sure it’s always up an running. It’s not like php applications that rely on nginx and php-pm services. To make sure we run the meilisearch in background we will use <strong>supervisor</strong> for the purpose.</p><p>We need also to decide whether we want Meilisearch to be accessible outside of the server to expose it’s api to other remote apps or even display the UI in dev mode. Or only accessible internally (in the server itself). If we want to make it accessible we need to use <strong>Nginx</strong> with <strong>Reverse proxy.</strong></p><p>👍🏻 In our example we will consider we need our Meilisearch to be accessible remotely too.</p><p>Let’s create a setup_meilisearch_app function that will accept as parameters all related details we described previously :</p><pre>setup_meilisearch_app() {<br>  local app_user=&quot;$1&quot;<br>  local domain=&quot;$2&quot;<br>  local app_path=&quot;$3&quot;<br>  local summary_file=&quot;$4&quot;<br>  local msport=&quot;$5&quot;<br><br>  # Magic<br><br>}</pre><p>First, let’s install Meilisearch :</p><pre>spinner &quot;Installing Meilisearch...&quot; &quot;curl -L https://install.meilisearch.com -o install-meili.sh &amp;&amp; chmod +x install-meili.sh &amp;&amp; ./install-meili.sh&quot;<br><br>mv ./meilisearch /usr/local/bin/<br>mkdir -p &quot;$app_path/data.ms&quot;<br>chown -R $app_user:$app_user &quot;$app_path/data.ms&quot;</pre><p>Then when generate a master key and log it in our summary file:</p><pre>meili_key=$(openssl rand -hex 16)<br>echo -e &quot;\033[0;32m🔐 Meilisearch master key:\033[0m $meili_key&quot;<br>echo -e &quot;🔐 Meilisearch master key: $meili_key&quot; &gt;&gt; &quot;$summary_file&quot;</pre><p>Now it’s supervisor time, let’s run the app in production mode, you can remove production flag if you want to use the <strong>Meilisearch UI</strong> :</p><pre>spinner &quot;Setting up Supervisor for Meilisearch&quot; &quot;bash -c &#39;<br>  cat &gt; /etc/supervisor/conf.d/meilisearch_${domain}.conf &lt;&lt;EOL<br>[program:meilisearch_${domain}]<br>command=/usr/local/bin/meilisearch --http-addr 127.0.0.1:${msport} --env production --db-path ${app_path}/data.ms --master-key ${meili_key} --experimental-enable=contains<br>autostart=true<br>autorestart=true<br>stderr_logfile=/var/log/meilisearch_${domain}.err.log<br>stdout_logfile=/var/log/meilisearch_${domain}.log<br>EOL<br>  &#39;&quot;<br><br>supervisorctl reread<br>supervisorctl update</pre><p>Now, we have our Meilisearch application up and running 🎉. The setup_meilisearch_app should look like this :</p><pre>setup_meilisearch_app() {<br>  local app_user=&quot;$1&quot;<br>  local domain=&quot;$2&quot;<br>  local app_path=&quot;$3&quot;<br>  local summary_file=&quot;$4&quot;<br>  local msport=&quot;$5&quot;<br><br>  spinner &quot;Installing Meilisearch...&quot; &quot;curl -L https://install.meilisearch.com -o install-meili.sh &amp;&amp; chmod +x install-meili.sh &amp;&amp; ./install-meili.sh&quot;<br><br>  mv ./meilisearch /usr/local/bin/<br>  mkdir -p &quot;$app_path/data.ms&quot;<br>  chown -R $app_user:$app_user &quot;$app_path/data.ms&quot;<br><br>  meili_key=$(openssl rand -hex 16)<br>  echo -e &quot;\033[0;32m🔐 Meilisearch master key:\033[0m $meili_key&quot;<br>  echo -e &quot;🔐 Meilisearch master key: $meili_key&quot; &gt;&gt; &quot;$summary_file&quot;<br><br>  spinner &quot;Setting up Supervisor for Meilisearch&quot; &quot;bash -c &#39;<br>  cat &gt; /etc/supervisor/conf.d/meilisearch_${domain}.conf &lt;&lt;EOL<br>[program:meilisearch_${domain}]<br>command=/usr/local/bin/meilisearch --http-addr 127.0.0.1:${msport} --env production --db-path ${app_path}/data.ms --master-key ${meili_key} --experimental-enable=contains<br>autostart=true<br>autorestart=true<br>stderr_logfile=/var/log/meilisearch_${domain}.err.log<br>stdout_logfile=/var/log/meilisearch_${domain}.log<br>EOL<br>  &#39;&quot;<br><br>  supervisorctl reread<br>  supervisorctl update<br><br>  echo -e &quot;\033[0;36m🚀 Meilisearch service started on internal port $msport\033[0m&quot;<br>}</pre><h3>Set up Nginx and SSL</h3><p>The final step we have now is to set proper Nginx configuration per application, depending on the application type. For better practice we will have a configuration file for every application.</p><p>Let’s create a setup_nginx function that will accept those parameters :</p><ul><li>Application domain name</li><li>Application path</li><li>Port</li><li>Php version</li><li>Application type</li><li>Meilisearch internal port</li><li>Skip SSL verification or not</li></ul><pre>setup_nginx() {<br>  local domain=&quot;$1&quot;<br>  local app_path=&quot;$2&quot;<br>  local port=&quot;$3&quot;<br>  local php_version=&quot;$4&quot;<br>  local app_type=&quot;$5&quot;<br>  local msport=&quot;$6&quot;<br>  local skip_ssl=&quot;$7&quot;<br><br>  # Magic<br>}</pre><p>Let’s define the config file path, this variable needs to be used only inside the function :</p><pre>local nginx_conf=&quot;/etc/nginx/sites-available/$domain&quot;</pre><p>For the nginx .conf file structure is a bit similar. Except for Meilisearch as it requires <strong>reverse proxy</strong> instead.</p><p>Example of Laravel nginx <strong>.conf</strong> file:</p><pre>server {<br>    listen 443; # add ssl after 443 if enabled<br><br>    server_name api.myapp.com;<br>    root /home/me/api.myapp.com/public;<br>    index index.php index.html;<br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br>    location ~ \.php$ {<br>        include snippets/fastcgi-php.conf;<br>        fastcgi_pass unix:/run/php/php8.4-fpm.sock;<br>    }<br>    location ~ /\.ht {<br>        deny all;<br>    }<br>}</pre><p>Example of React nginx <strong>.conf</strong> file:</p><pre>server {<br>    listen 443; # add ssl after 443 if enabled<br>    server_name myapp.com;<br>    root /home/me/myapp.com/dist;<br>    index index.html;<br>    location / {<br>        try_files $uri $uri/ /index.html?$query_string;<br>    }<br>    location ~ \.php$ {<br>        include snippets/fastcgi-php.conf;<br>        fastcgi_pass unix:/run/php/php8.4-fpm.sock;<br>    }<br>    location ~ /\.ht {<br>        deny all;<br>    }<br>}</pre><p>Example of Meilisearch nginx <strong>.conf</strong> file:</p><pre>server {<br>    listen 443; # add ssl after 443 if enabled<br>    server_name ms.myapp.com;<br>    root /home/apollo/ms.myapp.com;<br>    index index.php index.html;<br>    location / {<br>        proxy_pass http://127.0.0.1:7701;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><p>Now after you had an idea how the <strong>.conf</strong> file should look, let’s create a script that will generate it.</p><pre>{<br>  echo &quot;server {&quot;<br>  echo &quot;    listen ${port:-80};&quot;<br>  echo &quot;    server_name $domain;&quot;<br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>    echo &quot;    root $app_path/public;&quot;<br>  elif [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    echo &quot;    root $app_path/dist;&quot;<br>  else<br>    echo &quot;    root $app_path;&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    echo &quot;    index index.html index.htm index.nginx-debian.html;&quot;<br>  else<br>    echo &quot;    index index.php index.html index.htm index.nginx-debian.html;&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>    echo &quot;    location / {&quot;<br>    echo &quot;        proxy_pass http://127.0.0.1:$msport;&quot;<br>    echo &quot;        proxy_set_header Host \$host;&quot;<br>    echo &quot;        proxy_set_header X-Real-IP \$remote_addr;&quot;<br>    echo &quot;    }&quot;<br>  else<br>    echo &quot;    location / {&quot;<br>    if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>      echo &quot;        try_files \$uri \$uri/ /index.html;&quot;<br>    else<br>      echo &quot;        try_files \$uri \$uri/ /index.php?\$query_string;&quot;<br>    fi<br>    echo &quot;    }&quot;<br>    if [[ &quot;$app_type&quot; != &quot;react&quot; ]]; then<br>    echo &quot;    location ~ \.php\$ {&quot;<br>    echo &quot;        include snippets/fastcgi-php.conf;&quot;<br>    echo &quot;        fastcgi_pass unix:/run/php/php$php_version-fpm.sock;&quot;<br>    echo &quot;    }&quot;<br>    fi<br>    echo &quot;    location ~ /\.ht {&quot;<br>    echo &quot;        deny all;&quot;<br>    echo &quot;    }&quot;<br>  fi<br><br>  echo &quot;}&quot;<br>} &gt; &quot;$nginx_conf&quot;</pre><p>As you may remember, previously we want to support ability to generate SSL certificates. To do so we will stoip nginx service and run certbot command with --standalone flag. <strong><em>And that’s why we enabled port 80 previous in the UFW section.</em></strong></p><pre>systemctl stop nginx<br>print_status &quot;SSL for $domain&quot;<br>certbot certonly --standalone -d &quot;$domain&quot; --non-interactive --agree-tos -m admin@&quot;$domain&quot;<br>print_done &quot;SSL for $domain&quot;</pre><p>After that we will need to rewrite the .<strong>conf</strong> files, the script will look like this :</p><pre>{<br>  echo &quot;server {&quot;<br>  echo &quot;    listen ${port:-443} ssl;&quot;<br>  echo &quot;    server_name $domain;&quot;<br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>    echo &quot;    root $app_path/public;&quot;<br>  elif [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    echo &quot;    root $app_path/dist;&quot;<br>  else<br>    echo &quot;    root $app_path;&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    echo &quot;    index index.html;&quot;<br>  else<br>    echo &quot;    index index.php index.html;&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>    echo &quot;    location / {&quot;<br>    echo &quot;        proxy_pass http://127.0.0.1:$msport;&quot;<br>    echo &quot;        proxy_set_header Host \$host;&quot;<br>    echo &quot;        proxy_set_header X-Real-IP \$remote_addr;&quot;<br>    echo &quot;    }&quot;<br>  else<br>    echo &quot;    location / {&quot;<br>    if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    echo &quot;        try_files \$uri \$uri/ /index.html?\$query_string;&quot;<br>    else<br>    echo &quot;        try_files \$uri \$uri/ /index.php?\$query_string;&quot;<br>    fi<br>    echo &quot;    }&quot;<br>    echo &quot;    location ~ \.php\$ {&quot;<br>    echo &quot;        include snippets/fastcgi-php.conf;&quot;<br>    echo &quot;        fastcgi_pass unix:/run/php/php$php_version-fpm.sock;&quot;<br>    echo &quot;    }&quot;<br>    echo &quot;    location ~ /\.ht {&quot;<br>    echo &quot;        deny all;&quot;<br>    echo &quot;    }&quot;<br>  fi<br><br>  echo &quot;    ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;&quot;<br>  echo &quot;    ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;&quot;<br>  echo &quot;}&quot;<br>} &gt; &quot;$nginx_conf&quot;</pre><p>Now we have a function that can generate an nginx .conf file for each application type and depending on your SSL settings 🎉. The final setup_nginx function should look like this :</p><pre>setup_nginx() {<br>  local domain=&quot;$1&quot;<br>  local app_path=&quot;$2&quot;<br>  local port=&quot;$3&quot;<br>  local php_version=&quot;$4&quot;<br>  local app_type=&quot;$5&quot;<br>  local msport=&quot;$6&quot;<br>  local skip_ssl=&quot;$7&quot;<br><br>  local nginx_conf=&quot;/etc/nginx/sites-available/$domain&quot;<br><br>  {<br>    echo &quot;server {&quot;<br>    echo &quot;    listen ${port:-80};&quot;<br>    echo &quot;    server_name $domain;&quot;<br><br>    if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>      echo &quot;    root $app_path/public;&quot;<br>    elif [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>      echo &quot;    root $app_path/dist;&quot;<br>    else<br>      echo &quot;    root $app_path;&quot;<br>    fi<br><br>    if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>      echo &quot;    index index.html index.htm index.nginx-debian.html;&quot;<br>    else<br>      echo &quot;    index index.php index.html index.htm index.nginx-debian.html;&quot;<br>    fi<br><br>    if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>      echo &quot;    location / {&quot;<br>      echo &quot;        proxy_pass http://127.0.0.1:$msport;&quot;<br>      echo &quot;        proxy_set_header Host \$host;&quot;<br>      echo &quot;        proxy_set_header X-Real-IP \$remote_addr;&quot;<br>      echo &quot;    }&quot;<br>    else<br>      echo &quot;    location / {&quot;<br>      if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>        echo &quot;        try_files \$uri \$uri/ /index.html;&quot;<br>      else<br>        echo &quot;        try_files \$uri \$uri/ /index.php?\$query_string;&quot;<br>      fi<br>      echo &quot;    }&quot;<br>      if [[ &quot;$app_type&quot; != &quot;react&quot; ]]; then<br>      echo &quot;    location ~ \.php\$ {&quot;<br>      echo &quot;        include snippets/fastcgi-php.conf;&quot;<br>      echo &quot;        fastcgi_pass unix:/run/php/php$php_version-fpm.sock;&quot;<br>      echo &quot;    }&quot;<br>      fi<br>      echo &quot;    location ~ /\.ht {&quot;<br>      echo &quot;        deny all;&quot;<br>      echo &quot;    }&quot;<br>    fi<br><br>    echo &quot;}&quot;<br>  } &gt; &quot;$nginx_conf&quot;<br><br>  ln -s &quot;$nginx_conf&quot; /etc/nginx/sites-enabled/<br>  [[ -n &quot;$port&quot; ]] &amp;&amp; ufw allow &quot;$port&quot;/tcp &amp;&amp; ufw reload<br><br>  if [[ &quot;$skip_ssl&quot; == &quot;n&quot; ]]; then<br>    systemctl stop nginx<br>    print_status &quot;SSL for $domain&quot;<br>    certbot certonly --standalone -d &quot;$domain&quot; --non-interactive --agree-tos -m admin@&quot;$domain&quot;<br>    print_done &quot;SSL for $domain&quot;<br><br>    {<br>      echo &quot;server {&quot;<br>      echo &quot;    listen ${port:-443} ssl;&quot;<br>      echo &quot;    server_name $domain;&quot;<br><br>      if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>        echo &quot;    root $app_path/public;&quot;<br>      elif [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>        echo &quot;    root $app_path/dist;&quot;<br>      else<br>        echo &quot;    root $app_path;&quot;<br>      fi<br><br>      if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>        echo &quot;    index index.html;&quot;<br>      else<br>        echo &quot;    index index.php index.html;&quot;<br>      fi<br><br>      if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>        echo &quot;    location / {&quot;<br>        echo &quot;        proxy_pass http://127.0.0.1:$msport;&quot;<br>        echo &quot;        proxy_set_header Host \$host;&quot;<br>        echo &quot;        proxy_set_header X-Real-IP \$remote_addr;&quot;<br>        echo &quot;    }&quot;<br>      else<br>        echo &quot;    location / {&quot;<br>        if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>        echo &quot;        try_files \$uri \$uri/ /index.html?\$query_string;&quot;<br>        else<br>        echo &quot;        try_files \$uri \$uri/ /index.php?\$query_string;&quot;<br>        fi<br>        echo &quot;    }&quot;<br>        echo &quot;    location ~ \.php\$ {&quot;<br>        echo &quot;        include snippets/fastcgi-php.conf;&quot;<br>        echo &quot;        fastcgi_pass unix:/run/php/php$php_version-fpm.sock;&quot;<br>        echo &quot;    }&quot;<br>        echo &quot;    location ~ /\.ht {&quot;<br>        echo &quot;        deny all;&quot;<br>        echo &quot;    }&quot;<br>      fi<br><br>      echo &quot;    ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;&quot;<br>      echo &quot;    ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;&quot;<br>      echo &quot;}&quot;<br>    } &gt; &quot;$nginx_conf&quot;<br><br>    systemctl start nginx<br>  else<br>    echo -e &quot;\033[0;37mSSL skipped. Remember to set up SSL manually.\033[0m&quot;<br>  fi<br>}</pre><h3>Combine all functions in one Bash script</h3><p>Now after we went over all core features. Lets add them in our loop :</p><pre>app_index=1<br><br>while true; do<br>  echo -e &quot;\n\033[0;37m📦 Setting up app #$app_index\033[0m&quot;<br>  read -p $&#39;\033[0;32mEnter domain (e.g., app.example.com): \033[0m &#39; domain<br>  <br>  read -p $&#39;\033[0;32mEnter app port (or leave blank for HTTPS-only): \033[0m &#39; port<br><br>  app_type=$(printf &quot;laravel\nreact\nmeilisearch&quot; | fzf --prompt=&quot;Choose app type: &quot; --height=10 --reverse)<br><br>  if [[ -z &quot;$app_type&quot; ]]; then<br>    echo &quot;❌ No app type selected. Exiting.&quot;<br>    exit 1<br>  fi<br><br>  if [[ -n &quot;$port&quot; ]]; then<br>    if lsof -i :$port &amp;&gt;/dev/null; then<br>      echo -e &quot;\033[0;33m⚠️  Port $port is already in use.\033[0m&quot;<br>      existing_sites=$(grep -lr &quot;listen $port&quot; /etc/nginx/sites-available 2&gt;/dev/null | xargs -r grep -E &quot;server_name&quot; | awk &#39;{print $2}&#39; | tr -d &#39;;&#39;)<br>      if [[ -n &quot;$existing_sites&quot; ]]; then<br>        echo -e &quot;\033[0;33m🔍 Detected this port is already used by domain(s):\033[0m $existing_sites&quot;<br>        read -p $&#39;\033[0;32mAre you sure you want to continue using this port? (y/n): \033[0m &#39; continue_port<br>        if [[ &quot;$continue_port&quot; != &quot;y&quot; ]]; then<br>          echo &quot;Aborting due to port conflict.&quot;<br>          exit 1<br>        fi<br>      else<br>        echo -e &quot;\033[0;33mNo matching domain found for this port in NGINX, but it is in use.\033[0m&quot;<br>        read -p $&#39;\033[0;32mContinue anyway? (y/n): \033[0m &#39; continue_anyway<br>        if [[ &quot;$continue_anyway&quot; != &quot;y&quot; ]]; then<br>          echo &quot;Aborting due to port conflict.&quot;<br>          exit 1<br>        fi<br>      fi<br>    fi<br>  fi<br><br>  if [[ -z &quot;$port&quot; ]]; then<br>    port=443<br>  fi<br>  <br>  app_path=&quot;/home/$app_user/$domain&quot;<br><br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; || &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    read -p $&#39;\033[0;32mEnter Git repo URL: \033[0m &#39; repo_url<br>    clone_git_repo &quot;$repo_url&quot; &quot;$app_user&quot; &quot;$app_path&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;laravel&quot; ]]; then<br>    read -p $&#39;\033[0;32mInstall gRPC extension? (y/n): \033[0m &#39; install_grpc<br>    read -p $&#39;\033[0;32mDo you want to import a MySQL dump file? (y/n): \033[0m &#39; import_dump<br><br>    db_names=&quot;&quot;<br>    if [[ &quot;$import_dump&quot; == &quot;y&quot; ]]; then<br>        read -p $&#39;\033[0;32mEnter path to .zip or .7z dump file: \033[0m &#39; dump_path<br>        add_db=&quot;n&quot;<br>    else<br>        dump_path=&quot;&quot;<br>        read -p $&#39;\033[0;32mAdd a database for this app? (y/n): \033[0m &#39; add_db<br><br>        if [[ &quot;$add_db&quot; == &quot;y&quot; ]]; then<br>            while true; do<br>                read -p $&#39;\033[0;32mEnter DB name: \033[0m &#39; db_name<br>                db_names+=&quot;$db_name &quot;<br>                read -p $&#39;\033[0;32mAdd another DB? (y/n): \033[0m &#39; another_db<br>                [[ &quot;$another_db&quot; != &quot;y&quot; ]] &amp;&amp; break<br>            done<br>        fi<br>    fi<br><br>    read -p $&#39;\033[0;32mUse Supervisor for Laravel queue workers? (y/n): \033[0m &#39; use_sup<br>    if [[ &quot;$use_sup&quot; == &quot;y&quot; ]]; then<br>        read -p $&#39;\033[0;32mNumber of workers: \033[0m &#39; worker_count<br>        read -p $&#39;\033[0;32mQueue names (comma/default): \033[0m &#39; worker_queues<br>    else<br>        worker_count=0<br>        worker_queues=&quot;&quot;<br>    fi<br><br>    setup_laravel_app &quot;$app_path&quot; &quot;$php_version&quot; &quot;$app_user&quot; &quot;$domain&quot; &quot;$SUMMARY_FILE&quot; &quot;$add_db&quot; &quot;$db_names&quot; &quot;$use_sup&quot; &quot;$worker_count&quot; &quot;$worker_queues&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;react&quot; ]]; then<br>    setup_react_app &quot;$app_user&quot; &quot;$app_path&quot;<br>  fi<br><br>  if [[ &quot;$app_type&quot; == &quot;meilisearch&quot; ]]; then<br>    read -p $&#39;\033[0;32mEnter meilisearch internal port (Default 7700): \033[0m &#39; msport<br>    [[ -z &quot;$msport&quot; ]] &amp;&amp; msport=7700<br>    setup_meilisearch_app &quot;$app_user&quot; &quot;$domain&quot; &quot;$app_path&quot; &quot;$SUMMARY_FILE&quot; &quot;$msport&quot;<br>  fi<br><br>  setup_nginx &quot;$domain&quot; &quot;$app_path&quot; &quot;$port&quot; &quot;$php_version&quot; &quot;$app_type&quot; &quot;$msport&quot; &quot;$skip_ssl&quot;<br><br>  echo -e &quot;App URL: https://$domain:$port&quot; &gt;&gt; $SUMMARY_FILE<br><br>  read -p $&#39;\033[0;32mAdd another app? (y/n): \033[0m &#39; add_more<br>  [[ &quot;$add_more&quot; != &quot;y&quot; ]] &amp;&amp; break<br>  ((app_index++))<br>done</pre><h3>BONUS</h3><p>Thanks for making it this far! The full script is available on my public <a href="https://github.com/hosnyben/laravel-server-setup-bash">GitHub repository</a> — feel free to contribute.</p><p>The goal is simple: <strong><em>make the Laravel developer experience smoother, faster, and more transparent.</em></strong></p><p><strong>I highly encourage every developer to go through this kind of setup at least once before relying on deployment tools like </strong><a href="https://forge.laravel.com/"><strong>Laravel Forge</strong></a><strong>.</strong> These tools are fantastic and can save you tons of time, but nothing beats understanding what’s really happening under the hood.</p><p>See you next time! ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9b6968a1e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 11 : Authentication using JWT with asymmetric key and auth middleware]]></title>
            <link>https://medium.com/@hosnyben/laravel-11-authentication-using-jwt-with-asymmetric-key-and-auth-middleware-e61c7e5303d5?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/e61c7e5303d5</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 16:41:51 GMT</pubDate>
            <atom:updated>2024-07-03T16:41:51.190Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Laravel 11</strong> JWT Authentication: A Step-by-Step Guide with Asymmetric Keys</h3><p>Due to the specific requirements of your SaaS application, you might need more control over the authentication features. While Laravel offers robust authentication packages such as Sanctum, there are scenarios where you may prefer to implement custom authentication logic.</p><p>In this article, I will demonstrate how to create an out-of-the-box application that can serve as a template for your future projects. This will allow you to implement your custom authentication logic quickly and efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81mW_UF19lOwsraNohIxoA.png" /></figure><p>Let’s get started. We’ll assume that we’re working on a completely new Laravel 11 application. First, we need to create our application and navigate to its directory:</p><pre># Initialize the application called &quot;my-auth-app&quot;<br>composer create-project laravel/laravel my-auth-app<br><br>#Go to /my-auth-app folder<br>cd my-auth-app</pre><h3>Install dependencies</h3><p>To handle encoding and decoding JWTs, we need to install a suitable library. After reviewing available options on <a href="https://jwt.io/libraries?language=PHP">jwt.io</a>, I’ve decided to use the <a href="https://github.com/lcobucci/jwt"><strong>lcobucci/jwt</strong></a> library. Let’s proceed with the installation by running the following command in the console from the root directory of your application:</p><pre>composer require lcobucci/jwt</pre><h3>Set storage for private/public keys</h3><p>We may want to have a folder to store our private/public key</p><pre># Create /jwt folder in /storage<br>mkdir storage/jwt</pre><p>The issue we will face here is that the /jwt folder will be ignored in your git project as all storage content except /storage/public are ignored. To fix that let open our <strong>/storage/.gitignore </strong>and add /storage/jwt folder as exception by adding add !jwt/ under !public/:</p><p>The issue we will face here is that the /jwt folder will be ignored in your Git project since all storage content, except for /storage/public, is ignored by default. To fix this, we need to modify our /storage/.gitignore file and add the /storage/jwt folder as an exception. You can do this by adding the line !jwt/ under !public/:</p><pre>*<br>!public/<br>!jwt/<br>!.gitignore</pre><p>This will ensure that the /storage/jwt folder is tracked by Git.</p><p>For security reasons, it is crucial to keep the keys on the server and not include them in your Git repository. To ensure this, we need to create a .gitignore file inside the /storage/jwt folder. This file will prevent the keys from being tracked by Git.</p><p>Create the .gitignore file with the following content:</p><pre>*<br>!.gitignore</pre><p>With the above approach, you will have a secure folder on your server where you can store your public and private keys safely. This ensures that sensitive key information is not included in your Git repository, maintaining the security of your application.</p><h3>Create JwtHelper</h3><p>To maintain consistent and clean code, let’s avoid redundancy by creating a custom helper. This helper will allow us to store and manage our custom JWT configuration effectively.</p><pre># Create app/Helpers folder if it doesn&#39;t exists<br>mkdir app/Helpers<br><br># Create the helper file<br>touch app/Helpers/JwtHelper.php</pre><p>In this helper, we need to implement the getJwtConfiguration() method, which will return an instance of Lcobucci\JWT\Configuration. To achieve this, we first need to define the paths for the private and public keys.</p><p>Let’s start by defining the variables $privateKeyPath and $publicKeyPath to store these paths.</p><pre>// Ensure that Storage::path(&#39;jwt/private.pem&#39;) returns a non-empty string<br>$privateKeyPath = Storage::path(&#39;jwt/private.pem&#39;);<br>if (empty($privateKeyPath)) {<br>    throw new \InvalidArgumentException(&#39;Private key path cannot be empty.&#39;);<br>}<br><br>// Ensure that Storage::path(&#39;jwt/public.pem&#39;) returns a non-empty string<br>$publicKeyPath = Storage::path(&#39;jwt/public.pem&#39;);<br>if (empty($publicKeyPath)) {<br>    throw new \InvalidArgumentException(&#39;Public key path cannot be empty.&#39;);<br>}</pre><p>Now we need to create a configuration we’re going to use for all our interactions with tokens <em>(create and parse).</em> Based on <a href="https://lcobucci-jwt.readthedocs.io/en/stable/">lcobucci-lwt documentatio</a>, let’s return the configuration with Asymmetric signing involves a pair of keys: a private key for signing and a public key for verification with <strong>SHA-256 </strong>hashing algorithm.</p><p>Next, we need to create a configuration that will be used for all our interactions with tokens, including <strong>creation</strong> and <strong>parsing</strong>. According to the <a href="https://lcobucci-jwt.readthedocs.io/en/stable/">lcobucci/jwt documentation</a>, we’ll return the configuration with asymmetric signing, which involves a pair of keys: a <strong>private key</strong> for signing and a <strong>public key</strong> for verification, utilizing the <strong>SHA-256</strong> hashing algorithm.</p><pre>return Configuration::forAsymmetricSigner(<br>    new Sha256(),<br>    InMemory::file($privateKeyPath),<br>    InMemory::file($publicKeyPath)<br>);</pre><p>The file app/Helpers/JwtHelper.php will look like the following</p><pre>&lt;?php<br><br>namespace App\Helpers;<br>use Lcobucci\JWT\Configuration;<br>use Lcobucci\JWT\Signer\Rsa\Sha256;<br>use Lcobucci\JWT\Signer\Key\InMemory;<br><br>use Illuminate\Support\Facades\Storage;<br><br>class JwtHelper<br>{<br>    public static function getJwtConfiguration(): Configuration<br>    {<br>        // Ensure that Storage::path(&#39;jwt/private.pem&#39;) returns a non-empty string<br>        $privateKeyPath = Storage::path(&#39;jwt/private.pem&#39;);<br>        if (empty($privateKeyPath)) {<br>            throw new \InvalidArgumentException(&#39;Private key path cannot be empty.&#39;);<br>        }<br><br>        // Ensure that Storage::path(&#39;jwt/public.pem&#39;) returns a non-empty string<br>        $publicKeyPath = Storage::path(&#39;jwt/public.pem&#39;);<br>        if (empty($publicKeyPath)) {<br>            throw new \InvalidArgumentException(&#39;Public key path cannot be empty.&#39;);<br>        }<br><br>        return Configuration::forAsymmetricSigner(<br>            new Sha256(),<br>            InMemory::file($privateKeyPath),<br>            InMemory::file($publicKeyPath)<br>        );<br>    }<br>}</pre><p>You may wonder how to create private/public keys. Do not worry we will get to this part later ;)</p><h3>Set up User eloquent model</h3><p>For security purpose, we may add uuid records for our User model as we’re going to add <strong>user uuid</strong> in our token claims. Laravel offers a quick way to make your model supports uuid in <a href="https://laravel.com/docs/11.x/eloquent#uuid-and-ulid-keys">this section</a>. Let’s do it ;)</p><p>Now let’s use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the User model.</p><p>For security purposes, we should add <strong>UUID</strong> records to our User model since we’ll be including the user <strong>UUID</strong> in our token claims. Laravel provides a convenient way to enable UUID support for your models.</p><p>Let’s proceed by using the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the User model. Here’s how you can do it:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Concerns\HasUuids;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br><br>class User extends Authenticatable<br>{<br>    use HasUuids;<br><br>    // ...<br>}</pre><p>To ensure the auto increment of uuid let’s create a migration file to alter <strong>users</strong> table and add uuid column.</p><pre># Create migration file<br>php artisan make:migration AddUuidColumnToUsersTable</pre><p>Laravel will create a file in your /database/migrations folder similar to 2024_07_01_230045_add_uuid_column_to_users_table.php. Let’s open the file and copy/paste the following code.</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            // We add the uuid column right after the id<br>            $table-&gt;uuid(&#39;uuid&#39;)-&gt;unique()-&gt;after(&#39;id&#39;)-&gt;index();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            // Drop the uuid column<br>            $table-&gt;dropColumn(&#39;uuid&#39;);<br>        });<br>    }<br>};</pre><h3>Have extra control over tokens</h3><p>To have control on generated tokens we may need to create a jwt_tokens table to store tokens and validate their important records like <strong>permissions</strong>, <strong>user_uuid</strong>, <strong>unique_id</strong>, <strong>description</strong>, <strong>expiration date</strong>, and maybe <strong>last used time</strong>.</p><p>To have control over the generated tokens, we need to create a jwt_tokens table to store tokens and validate their important attributes, such as <strong>permissions</strong>, <strong>user_uuid</strong>, <strong>unique_id</strong>, <strong>description</strong>, <strong>expiration date</strong>, and possibly the <strong>last used time</strong>.</p><p>We don’t have to create an eloquent model for that so let’s just create a migration file to create the table.</p><pre># Create migration file<br>php artisan make:migration CreateJwtTokensTable</pre><p>Laravel will create a file in your /database/migrations folder similar to 2024_07_01_233530_create_jwt_tokens_table.php. Let’s open the file and copy/paste the following code.</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;jwt_tokens&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;uuid(&#39;user_uuid&#39;);<br>            // Foreign key to uuid column of users table <br>            $table-&gt;foreign(&#39;user_uuid&#39;)-&gt;references(&#39;uuid&#39;)-&gt;on(&#39;users&#39;)-&gt;onDelete(&#39;cascade&#39;);<br>            $table-&gt;string(&#39;unique_id&#39;)-&gt;unique()-&gt;index();<br>            $table-&gt;string(&#39;description&#39;);<br>            $table-&gt;json(&#39;permissions&#39;)-&gt;nullable();<br>            $table-&gt;timestamps();<br>            $table-&gt;timestamp(&#39;expires_at&#39;)-&gt;nullable();<br>            $table-&gt;timestamp(&#39;last_used_at&#39;)-&gt;nullable();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;jwt_tokens&#39;);<br>    }<br>};</pre><h3>Token manipulation</h3><p>All token operations are related to <strong>User</strong> model. Let’s create a trait to <strong>create/destroy</strong> token.</p><pre># Create app/Traits folder where we sotre the trait file<br>mkdir app/Traits<br><br># Create app/Traits/JWTAuthTrait.php file<br>touch app/Traits/JWTAuthTrait.php</pre><p>Let’s call the config :</p><pre>use App\Helpers\JwtHelper;<br><br>$config = JwtHelper::getJwtConfiguration();</pre><p>Now, we generate the token :</p><pre>$date = new \DateTimeImmutable();<br>$uniqueID = uniqid();<br><br>// Generate the token with appropriate claims<br>$token = $config-&gt;builder()<br>    -&gt;issuedBy(config(&#39;app.url&#39;)) // Configures the issuer (iss claim)<br>    -&gt;permittedFor(config(&#39;app.url&#39;)) // Configures the audience (aud claim)<br>    -&gt;identifiedBy($uniqueID) // Configures the id (jti claim)<br>    -&gt;relatedTo($this-&gt;uuid) // Configures the subject (sub claim)<br>    -&gt;issuedAt($date) // Configures the time that the token was issued (iat claim)<br>    -&gt;canOnlyBeUsedAfter($date) // Configures the time that the token can be used (nbf claim)<br>    -&gt;expiresAt($date-&gt;modify(&#39;+1 week&#39;)) // Configures the expiration time of the token (exp claim)<br>    -&gt;getToken($config-&gt;signer(), $config-&gt;signingKey()); // Retrieves the generated token</pre><p>In the above code, we initiate the configuration. For enhanced security, we generate the token in compliance with the <a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519</a> guidelines. To achieve this, we need to provide the required claims:<br>- issuedBy to add “<strong>iss” (Issuer)</strong><br>- permittedFor to add “<strong>aud” </strong>(<strong>Audience)</strong><br>- identifiedBy to add “j<strong>ti” (JWT ID)</strong><br>- relatedTo to add “<strong>sub” (Subject)</strong><br>- issuedAt to add <strong>“iat” (Issued At)</strong><br>- canOnlyBeUsedAfter to add <strong>“nbf” (Not Before)<br>- </strong>expiresAt to add <strong>“exp” (Expiration Time)</strong></p><p>After the token is generated, let’s add it to our <strong>jwt_tokens</strong> table. Here’s an example of how you can achieve this:</p><pre>// insert the token record in database<br>DB::table(&#39;jwt_tokens&#39;)-&gt;insert([<br>    &#39;user_uuid&#39; =&gt; $this-&gt;uuid,<br>    &#39;unique_id&#39; =&gt; $uniqueID,<br>    &#39;description&#39; =&gt; $action.&quot; &quot;.$this-&gt;email,<br>    &#39;permissions&#39; =&gt; null,<br>    &#39;expires_at&#39; =&gt; $date-&gt;modify($expiration),<br>    &#39;last_used_at&#39; =&gt; null,<br>    &#39;created_at&#39; =&gt; $date,<br>    &#39;updated_at&#39; =&gt; $date,<br>]);</pre><p>To destroy a token, the only operation we need is to remove the token from <strong>jwt_tokens</strong> table.</p><pre>// Delete the token record<br>!DB::table(&#39;jwt_tokens&#39;)-&gt;where([<br>    &#39;unique_id&#39; =&gt; $uniqueID,<br>    &#39;user_uuid&#39; =&gt; $this-&gt;uuid<br>])-&gt;delete()</pre><p>The file app/Traits/JWTAuthTrait.php will look like this:</p><pre>&lt;?php<br><br>namespace App\Traits;<br><br>use App\Helpers\JwtHelper;<br><br>use Illuminate\Support\Facades\DB;<br><br>trait JWTAuthTrait<br>{<br>    public function createToken(string $action = &#39;authToken&#39;, string $expiration = &#39;+1 week&#39;): string<br>    {<br>        // Ensure $this-&gt;uuid is a non-empty string<br>        if (empty($this-&gt;uuid)) {<br>            return &#39;&#39;;<br>        }<br><br>        $config = JwtHelper::getJwtConfiguration();<br>        $date = new \DateTimeImmutable();<br>        $uniqueID = uniqid();<br><br>        // Generate the token with appropriate claims<br>        $token = $config-&gt;builder()<br>            -&gt;issuedBy(config(&#39;jwt.issuer&#39;)) // Configures the issuer (iss claim)<br>            -&gt;permittedFor(config(&#39;jwt.audience&#39;)) // Configures the audience (aud claim)<br>            -&gt;identifiedBy($uniqueID) // Configures the id (jti claim)<br>            -&gt;relatedTo($this-&gt;uuid) // Configures the subject (sub claim)<br>            -&gt;issuedAt($date) // Configures the time that the token was issued (iat claim)<br>            -&gt;canOnlyBeUsedAfter($date) // Configures the time that the token can be used (nbf claim)<br>            -&gt;expiresAt($date-&gt;modify($expiration)) // Configures the expiration time of the token (exp claim)<br>            -&gt;getToken($config-&gt;signer(), $config-&gt;signingKey()); // Retrieves the generated token<br><br>        // insert the token record in database<br>        DB::table(&#39;jwt_tokens&#39;)-&gt;insert([<br>            &#39;user_uuid&#39; =&gt; $this-&gt;uuid,<br>            &#39;unique_id&#39; =&gt; $uniqueID,<br>            &#39;description&#39; =&gt; $action.&quot; &quot;.$this-&gt;email,<br>            &#39;permissions&#39; =&gt; null,<br>            &#39;expires_at&#39; =&gt; $date-&gt;modify($expiration),<br>            &#39;last_used_at&#39; =&gt; null,<br>            &#39;created_at&#39; =&gt; $date,<br>            &#39;updated_at&#39; =&gt; $date,<br>        ]);<br><br>        $this-&gt;token = $token-&gt;toString();<br><br>        return $token-&gt;toString();<br>    }<br><br>    public function destroyToken(string $tokenString): void<br>    {<br>        if (empty($tokenString)) {<br>            throw new \Exception(&#39;Token string is empty&#39;);<br>        }<br><br>        // Parse token<br>        $config = JwtHelper::getJwtConfiguration();<br>        $token = $config-&gt;parser()-&gt;parse($tokenString);<br><br>        if (!method_exists($token, &#39;claims&#39;)) {<br>            throw new \Exception(&quot;Invalid Token&quot;, 1);<br>        }<br><br>        // Check if the token belongs to the user<br>        $userUUID = $token-&gt;claims()-&gt;get(&#39;sub&#39;);<br>        $uniqueID = $token-&gt;claims()-&gt;get(&#39;jti&#39;);<br><br>        if (!$userUUID || !$uniqueID || $this-&gt;uuid !== $userUUID) {<br>            throw new \Exception(&#39;Invalid token&#39;);<br>        }<br><br>        if(<br>            // Delete the token record<br>            !DB::table(&#39;jwt_tokens&#39;)-&gt;where([<br>                &#39;unique_id&#39; =&gt; $uniqueID,<br>                &#39;user_uuid&#39; =&gt; $this-&gt;uuid<br>            ])-&gt;delete()<br>        ) {<br>            throw new \Exception(&#39;Invalid token&#39;);<br>        }<br>    }<br>}</pre><p>Now let’s use this trait in the <strong>User</strong> model:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Concerns\HasUuids;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br><br>use App\Traits\JWTAuthTrait;<br><br>class User extends Authenticatable<br>{<br>    use HasUuids;<br>    use JWTAuthTrait;<br><br>    // ...<br>}</pre><h3>Create custom guard</h3><p>Let’s proceed by creating a custom guard in the app/Guards directory. If the directory does not already exist, make sure to create it.</p><pre># Create the folder<br>mkdir app/Guards<br><br>#create the guard file<br>touch app/Guards/JwtGuard.php</pre><p>Next, copy and paste the following content. To implement the Guard class correctly, ensure that you define all the necessary methods: check, guest, user, id, validate, hasUser, setUser, and attempt. This will ensure that the Guard class adheres to the required structure.</p><p>Let’s proceed by creating the constructor:</p><pre>protected $user;<br>protected UserProvider $provider;<br>protected Request $request;<br>protected Configuration $config;<br><br>public function __construct(UserProvider $provider, Request $request)<br>{<br>    // Define the Provide and The Request incoming from the middleware<br>    $this-&gt;provider = $provider;<br>    $this-&gt;request = $request;<br><br>    // Define the auth configuration we need in the guard<br>    $this-&gt;config = JwtHelper::getJwtConfiguration();<br>}</pre><p>In the constructor, we define the following dependencies: Illuminate\Http\Request, Illuminate\Contracts\Auth\UserProvider, and the JWT configuration from our custom helper, App\Helpers\JwtHelper::getJwtConfiguration.</p><p>Now let’s retrieve the user:</p><pre>public function user()<br>{<br>    // check if it&#39;s already defined to skip the process<br>    if ($this-&gt;hasUser()) {<br>        return $this-&gt;user;<br>    }<br><br>    try {<br>        // Check if we have the bearer token with the ncoming Request<br>        $token = $this-&gt;request-&gt;bearerToken();<br><br>        if (!$token) {<br>            return null;<br>        }<br><br>        // If token exists let&#39;s parse it, based on our private/public keys<br>        $token = $this-&gt;config-&gt;parser()-&gt;parse($token);<br><br>        if(!method_exists($token, &#39;claims&#39;)) {<br>            return null;<br>        }<br><br>        // Check if there are any token constraints<br>        $constraints = $this-&gt;config-&gt;validationConstraints();<br><br>        if(!empty($constraints)) {<br>            // If constraints exists let&#39;s validate them<br>            $this-&gt;config-&gt;validator()-&gt;assert($token, ...$constraints);<br>        }<br><br>        // Retrive the user_uuid claim, stop the process if is missing<br>        $uuid = $token-&gt;claims()-&gt;get(&#39;sub&#39;);<br><br>        if(!$uuid) {<br>            return null;<br>        }<br><br>        // Check if user exists with the uuid above<br>        $user = User::where(&#39;uuid&#39;, $uuid)-&gt;first();<br><br>        if(!$user) {<br>            return null;<br>        }<br><br>        // We set the user matching the records and we validate the token<br>        $this-&gt;setUser($user);<br>        $this-&gt;validateToken($token);<br><br>        return $this-&gt;user;<br>    } catch (\Exception $e) {<br>        return null;<br>    }<br>}</pre><ol><li>We check first if the user already defined so we can skip the process</li><li>If not, we check then if the Bearer token exists in the request, if not we skip the process</li><li>We check if the token has some constraints, if yes we validate the constraints.</li><li>We get the user uuid from the <strong>“sub”</strong> claim</li><li>If user exists, we set it in our guard then we verify if the token is valid, it’s in this step where we wanted to have the <strong>jwt_tokens</strong> table to have control to disable a token even if it was valid.</li></ol><pre>private function validateToken($token)<br>{<br>    if (!$this-&gt;hasUser()) {<br>        throw new \Exception(&#39;No user set&#39;);<br>    }<br><br>    if(!method_exists($token, &#39;claims&#39;)) {<br>        throw new \Exception(&#39;Invalid token&#39;);<br>    }<br><br>    // Check if token exists, belong to the user and not expired<br>    $recordExists = DB::table(&#39;jwt_tokens&#39;)<br>                        -&gt;where([<br>                            &#39;unique_id&#39; =&gt; $token-&gt;claims()-&gt;get(&#39;jti&#39;),<br>                            &#39;user_uuid&#39; =&gt; $this-&gt;user-&gt;uuid<br>                        ])<br>                        -&gt;where(&#39;expires_at&#39;, &#39;&gt;&#39;, now())<br>                        -&gt;exists();<br><br>    if(!$recordExists) {<br>        throw new \Exception(&#39;Invalid token&#39;);<br>    }<br>}</pre><p>For the other methods, they are similar to those in other authentication guards. You can copy and paste the following code for the complete app/Guards/JwtGuard.php:</p><pre>&lt;?php<br><br>namespace App\Guards;<br><br>use Lcobucci\JWT\Configuration;<br><br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Contracts\Auth\Guard;<br>use Illuminate\Contracts\Auth\UserProvider;<br><br>use App\Helpers\JwtHelper;<br><br>use App\Models\User;<br>use Illuminate\Support\Facades\Hash;<br><br>class JwtGuard implements Guard<br>{<br>    /**<br>     * @var User | null $user The user.<br>     * @var UserProvider $provider The user provider.<br>     * @var Request $request The request.<br>     * @var Configuration $config The JWT configuration.<br>     */<br>    protected $user;<br>    protected UserProvider $provider;<br>    protected Request $request;<br>    protected Configuration $config;<br><br>    public function __construct(UserProvider $provider, Request $request)<br>    {<br>        // Define the Provide and The Request incoming from the middleware<br>        $this-&gt;provider = $provider;<br>        $this-&gt;request = $request;<br><br>        // Define the auth configuration we need in the guard<br>        $this-&gt;config = JwtHelper::getJwtConfiguration();<br>    }<br><br>    // Check if the the user already defined<br>    public function check()<br>    {<br>        return !is_null($this-&gt;user());<br>    }<br><br>    public function guest()<br>    {<br>        return !$this-&gt;check();<br>    }<br><br>    // The process to define the user making the request<br>    public function user()<br>    {<br>        // check if it&#39;s already defined to skip the process<br>        if ($this-&gt;hasUser()) {<br>            return $this-&gt;user;<br>        }<br><br>        try {<br>            // Check if we have the bearer token with the ncoming Request<br>            $token = $this-&gt;request-&gt;bearerToken();<br><br>            if (!$token) {<br>                return null;<br>            }<br><br>            // If token exists let&#39;s parse it, based on our private/public keys<br>            $token = $this-&gt;config-&gt;parser()-&gt;parse($token);<br><br>            if(!method_exists($token, &#39;claims&#39;)) {<br>                return null;<br>            }<br><br>            // Check if there are any token constraints<br>            $constraints = $this-&gt;config-&gt;validationConstraints();<br><br>            if(!empty($constraints)) {<br>                // If constraints exists let&#39;s validate them<br>                $this-&gt;config-&gt;validator()-&gt;assert($token, ...$constraints);<br>            }<br><br>            // Retrive the user_uuid claim, stop the process if is missing<br>            $uuid = $token-&gt;claims()-&gt;get(&#39;sub&#39;);<br><br>            if(!$uuid) {<br>                return null;<br>            }<br><br>            // Check if user exists with the uuid above<br>            $user = User::where(&#39;uuid&#39;, $uuid)-&gt;first();<br><br>            if(!$user) {<br>                return null;<br>            }<br><br>            // We set the user matching the records and we validate the token<br>            $this-&gt;setUser($user);<br>            $this-&gt;validateToken($token);<br><br>            return $this-&gt;user;<br>        } catch (\Exception $e) {<br>            return null;<br>        }<br>    }<br><br>    public function id()<br>    {<br>        return $this-&gt;user() ? $this-&gt;user()-&gt;getAuthIdentifier() : null;<br>    }<br><br>    /**<br>     * Validate a user&#39;s credentials.<br>     *<br>     * @param array&lt;mixed&gt; $credentials User credentials.<br>     * @return bool Always returns false, as this method is not applicable for JWT Guard.<br>     */<br>    public function validate(array $credentials = []): bool<br>    {<br>        // This method is not applicable for JWT Guard<br>        return false;<br>    }<br><br>    public function hasUser()<br>    {<br>        return !is_null($this-&gt;user);<br>    }<br><br>    /**<br>     * Set the user.<br>     * @param \App\Models\User $user The user to set.<br>     * @return $this<br>     */<br>    public function setUser($user)<br>    {<br>        $this-&gt;user = $user;<br>        return $this;<br>    }<br><br>    /**<br>     * Validate the token<br>     * @param \Lcobucci\JWT\Token $token The token to destroy.<br>     * @return void<br>     * @throws \Exception If the token is invalid.<br>     */<br>    private function validateToken($token)<br>    {<br>        if (!$this-&gt;hasUser()) {<br>            throw new \Exception(&#39;No user set&#39;);<br>        }<br><br>        if(!method_exists($token, &#39;claims&#39;)) {<br>            throw new \Exception(&#39;Invalid token&#39;);<br>        }<br><br>        // Check if token exists, belong to the user and not expired<br>        $recordExists = DB::table(&#39;jwt_tokens&#39;)<br>                            -&gt;where([<br>                                &#39;unique_id&#39; =&gt; $token-&gt;claims()-&gt;get(&#39;jti&#39;),<br>                                &#39;user_uuid&#39; =&gt; $this-&gt;user-&gt;uuid<br>                            ])<br>                            -&gt;where(&#39;expires_at&#39;, &#39;&gt;&#39;, now())<br>                            -&gt;exists();<br><br>        if(!$recordExists) {<br>            throw new \Exception(&#39;Invalid token&#39;);<br>        }<br>    }<br><br>    /**<br>     * Attempt to authenticate a user using the given credentials.<br>     * @param array&lt;mixed&gt; $credentials User credentials.<br>     * @param bool $remember Whether to remember the user.<br>     * @return void<br>     * @throws \Exception If the authentication attempt fails.<br>     */<br>    public function attempt(array $credentials = [], $remember = false)<br>    {<br>        $user = User::where(&#39;email&#39;, $credentials[&#39;email&#39;])-&gt;first();<br><br>        if (!$user || !Hash::check($credentials[&#39;password&#39;], $user-&gt;password)) {<br>            throw new \Exception(__(&#39;auth.failed&#39;));<br>        } else {<br>            $this-&gt;setUser($user);<br>        }<br>    }<br>}</pre><h3>To take our custom authentication into action</h3><p>The final step now is to define the middleware and make our custom authentication as the default.</p><p>Let’s define the middlware. Go to app/Providers/AppServiceProvider.php and add the following code in the boot() method:</p><pre>Auth::extend(&#39;jwt&#39;, function (Application $app, string $name, array $config) {<br>    $userProvider = Auth::createUserProvider($config[&#39;provider&#39;]);<br><br>    if (!$userProvider) {<br>        // Handle the null case, e.g., throw an exception or provide a default UserProvider<br>        throw new \Exception(&quot;User provider cannot be null.&quot;);<br>    }<br><br>    return new JwtGuard(<br>        $userProvider,<br>        $app-&gt;make(&#39;request&#39;)<br>    );<br>});</pre><p>Your app/Providers/AppServiceProvider.php must look like this :</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use App\Guards\JwtGuard;<br>use Illuminate\Support\Facades\Auth;<br>use Illuminate\Support\ServiceProvider;<br>use Illuminate\Contracts\Foundation\Application;<br><br>class AppServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register any application services.<br>     */<br>    public function register(): void<br>    {<br>        //<br>    }<br><br>    /**<br>     * Bootstrap any application services.<br>     */<br>    public function boot(): void<br>    {<br>        // Register the JWT guard<br>        Auth::extend(&#39;jwt&#39;, function (Application $app, string $name, array $config) {<br>            $userProvider = Auth::createUserProvider($config[&#39;provider&#39;]);<br><br>            if (!$userProvider) {<br>                // Handle the null case, e.g., throw an exception or provide a default UserProvider<br>                throw new \Exception(&quot;User provider cannot be null.&quot;);<br>            }<br><br>            return new JwtGuard(<br>                $userProvider,<br>                $app-&gt;make(&#39;request&#39;)<br>            );<br>        });<br>    }<br>}</pre><p>Now that we have defined our new authentication guard, let’s set the application to use it by default. Navigate to config/auth.php, where you’ll see that the default guard is <strong>“web”</strong> if it is not explicitly defined in the .env variables.</p><pre>&lt;?php<br><br>return [<br><br>    /*<br>    |--------------------------------------------------------------------------<br>    | Authentication Defaults<br>    |--------------------------------------------------------------------------<br>    |<br>    | This option defines the default authentication &quot;guard&quot; and password<br>    | reset &quot;broker&quot; for your application. You may change these values<br>    | as required, but they&#39;re a perfect start for most applications.<br>    |<br>    */<br><br>    &#39;defaults&#39; =&gt; [<br>        &#39;guard&#39; =&gt; env(&#39;AUTH_GUARD&#39;, &#39;web&#39;),<br>        &#39;passwords&#39; =&gt; env(&#39;AUTH_PASSWORD_BROKER&#39;, &#39;users&#39;),<br>    ],<br>    // ...<br>]</pre><p>Let’s add a new guard named <strong>“api”</strong>. In the same file, if you scroll down slightly, you’ll find the <strong>“guards”</strong> section. Here, you can add as many guards as needed. Our new guard should look like this:</p><pre>&lt;?php<br><br>return [<br>    // ...<br><br>    &#39;guards&#39; =&gt; [<br>        &#39;web&#39; =&gt; [<br>            &#39;driver&#39; =&gt; &#39;session&#39;,<br>            &#39;provider&#39; =&gt; &#39;users&#39;,<br>        ],<br>        &#39;api&#39; =&gt; [<br>            &#39;driver&#39; =&gt; &#39;jwt&#39;,<br>            &#39;provider&#39; =&gt; &#39;users&#39;,<br>        ],<br>    ],<br><br>// ...<br>]</pre><p>You can now just go to your .env file and add <strong>AUTH_GUARD=”api”.</strong></p><p>Congratulations, you just set your guard :)</p><h3><strong>Authentication middlware with you custom guard in Action</strong></h3><p>Now, the most important part is how to secure our HTTP requests using the newly configured guard. To do this, simply apply the auth:api middleware to your routes as follows:</p><pre>Route::middleware(&#39;auth:api&#39;)-&gt;group(function () {<br>    // Your protected routes<br>})</pre><h3>Generate private/public keys</h3><p>You may wonder in what step we can generate the keys in the storage we created before. To make sure we have an out-of-the-box application, we will create a console command to generate is for us.</p><p>We will make a prompt console where we will write our passphrase to generate both private and public keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*oLVITJs9FaXI3z8LogCh6w.gif" /><figcaption>Generate keys with console command</figcaption></figure><p>First let’s create the console command file</p><pre>php artisan make:command GenerateTokenKeys</pre><p>The command will create a file in app/Console/Commands/GenerateTokenKeys.php</p><p>Then copy/paste the following code into it :</p><pre>&lt;?php<br><br>namespace App\Console\Commands;<br><br>use Illuminate\Console\Command;<br>use Illuminate\Support\Facades\Storage;<br><br>class GenerateTokenKeys extends Command<br>{<br>    /**<br>     * The name and signature of the console command.<br>     *<br>     * @var string<br>     */<br>    protected $signature = &#39;app:generate-token-keys&#39;;<br><br>    /**<br>     * The console command description.<br>     *<br>     * @var string<br>     */<br>    protected $description = &#39;Command to generate public and private keys for JWT.&#39;;<br><br>    /**<br>     * Execute the console command.<br>     */<br>    public function handle(): void<br>    {<br>        // Ask for the passphrase<br>        $passphrase = $this-&gt;secret(&#39;Enter the passphrase for the private key&#39;);<br>        $passphraseConfirm = $this-&gt;secret(&#39;Confirm the passphrase for the private key&#39;);<br><br>        if ($passphrase !== $passphraseConfirm) {<br>            $this-&gt;error(&#39;The passphrases do not match.&#39;);<br>            return;<br>        }<br><br>        // Generate the private key<br>        $privateKey = Storage::path(&#39;jwt/private.pem&#39;);<br>        $command = &quot;openssl genrsa -passout pass:{$passphrase} -out {$privateKey}&quot;;<br>        exec($command);<br><br>        // Generate the public key<br>        $publicKey = Storage::path(&#39;jwt/public.pem&#39;);<br>        $command = &quot;openssl rsa -in {$privateKey} -passin pass:{$passphrase} -pubout -out {$publicKey}&quot;;<br>        exec($command);<br><br><br>        $this-&gt;info(&#39;Public and private keys have been generated successfully.&#39;);<br>    }<br>}</pre><p>And voila! We’re good to go.</p><h3><strong>BONUS</strong></h3><p>Thank you for reading till this section, as a bonus for you, let’s create a console command that will remove the expired token from <strong>jwt_tokens </strong>table and schedule it to run everyday.</p><p>First, let create console command file. Please run the following command in your console :</p><pre>php artisan make:command RemoveExpiredTokens</pre><p>Let’s copy/paste the following code into it:</p><pre>&lt;?php<br><br>namespace App\Console\Commands;<br><br>use Illuminate\Console\Command;<br>use Illuminate\Support\Facades\DB;<br><br>class RemoveExpiredTokens extends Command<br>{<br>    /**<br>     * The name and signature of the console command.<br>     *<br>     * @var string<br>     */<br>    protected $signature = &#39;app:remove-expired-tokens&#39;;<br><br>    /**<br>     * The console command description.<br>     *<br>     * @var string<br>     */<br>    protected $description = &#39;Command will be scheduled to remove expired tokens.&#39;;<br><br>    /**<br>     * Execute the console command.<br>     */<br>    public function handle(): void<br>    {<br>        // Get the current date and time<br>        $date = new \DateTimeImmutable();<br><br>        // Remove expired tokens<br>        DB::table(&#39;jwt_tokens&#39;)-&gt;where(&#39;expires_at&#39;, &#39;&lt;&#39;, $date)-&gt;delete();<br>    }<br>}</pre><p>Now, we need to let the console executes everyday. Please open the routes/console.php file and add the following line in the end</p><pre>Schedule::command(&#39;app:remove-expired-tokens&#39;)-&gt;daily();</pre><h3><strong>Conclusion</strong></h3><p>In conclusion, setting up JWT authentication with asymmetric keys and custom middleware in Laravel 11 enhances security and flexibility for your SaaS applications. This guide walks you through creating a secure folder for key storage, implementing a JwtHelper for configuration, adding UUID support to the User model, and managing tokens with a jwt_tokens table.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e61c7e5303d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating a 7-Year-Old WordPress Business to Laravel]]></title>
            <link>https://medium.com/@hosnyben/migrating-a-7-year-old-wordpress-business-to-laravel-bf9f11542fc1?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9f11542fc1</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 05:04:12 GMT</pubDate>
            <atom:updated>2024-04-15T05:04:12.443Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Technical Deep Dive</h4><p>Migrating a long-standing WordPress site to a more robust framework like <strong>Laravel</strong> paired with <strong>Vue/Vite</strong> for a <strong>single-page application (SPA)</strong> presents numerous challenges and opportunities. The project in question <em>— a booking website for notable attractions in Marrakesh — </em>required a complete overhaul in architecture, addition of new features, and a multitude of other improvements.</p><p><em>This article explores my technical journey of this migration, detailing the solutions implemented to address each challenge.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BobFcGlr8yDTXSQpk1mnUg.jpeg" /></figure><h4>Redesigning the Architecture</h4><p><strong>Challenge:</strong> The original WordPress architecture utilized multiple <strong>Post Types</strong> (Projects, Reservations, Rates) managed by <a href="https://advancedcustomfields.com/"><strong>Advanced Custom Fields (ACF)</strong></a>, resulting in a highly flexible but <strong>loosely</strong> structured data model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*F_QoYRTb5NLxWmsQdj4Unw.png" /><figcaption>Picture from : <a href="https://www.krishaweb.com/blog/laravel-vs-wordpress/">https://www.krishaweb.com/blog/laravel-vs-wordpress/</a></figcaption></figure><p><strong>Solution:</strong> Transitioning to Laravel required a more defined schema, leading to a critical decision between using <strong>MySQL</strong> or <strong>MongoDB</strong>. Given the diverse data requirements — for instance, some projects required both arrival and departure dates, others only an arrival date, and some demanded specific seating preferences such as table placements near windows or balconies — MongoDB’s schema-less nature was tempting. This would allow for dynamic adjustments to fields based on project types, facilitating the handling of various reservation requirements.</p><p>However, the need for structured CRUD operations, complex joins, and transactions highlighted MySQL’s advantages. Thus, a hybrid approach was chosen: MySQL maintained structured essential columns, while dynamic information that varied by project type was stored in JSON-formatted columns.</p><p>This approach provided both the necessary flexibility of a NoSQL database and the relational integrity and efficiency of a SQL database, ensuring a robust, scalable system capable of supporting complex data operations while accommodating the unique characteristics of different projects.</p><h4>Implementing New Features</h4><p><strong>Challenge:</strong> The existing site lacked certain modern functionalities that could enhance user experience and operational efficiency.</p><p><strong>Solution:</strong> Laravel’s robust background job processing was leveraged to implement automated features such as reminder notifications via queued jobs, which were sent to customers a day before their reservations. Integration with SMS APIs allowed for direct communication with clients, enhancing the booking experience.</p><h4>Maintaining SEO in an SPA</h4><p><strong>Challenge:</strong> One of the biggest challenges in migrating to a single-page application (SPA) was maintaining the search engine optimization (SEO) status that the WordPress site had achieved over its 7-year lifespan. SPAs typically load content dynamically using JavaScript, which can pose issues for search engine crawlers that rely on pre-rendered content, and can lead to a drop in SEO performance..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ug3WZqFeFcpUMa6cDpq5kA.png" /><figcaption>Picture From : <a href="https://refinery89.com/seo-for-publishers-how-to-start-optimizing/">https://refinery89.com/seo-for-publishers-how-to-start-optimizing/</a></figcaption></figure><p><strong>Solution:</strong> To counteract this, implementing server-side rendering (SSR) became essential. SSR technology pre-renders the webpage on the server, creating HTML content before it reaches the client, ensuring that search engine crawlers can access and index the site as if it were a traditional multi-page website.</p><p>Choosing the right technology for SSR involved considering both <strong>Node.js</strong> and <strong>Laravel</strong>, as each offers robust support for SSR. Node.js is well-regarded for its performance in server-side operations and might seem like a natural fit for SSR. However, since the API and the backend logic were already developed using Laravel, continuing with Laravel for SSR was the most practical choice.</p><p>This decision not only simplified the development process by keeping the stack consistent but also leveraged Laravel’s capabilities in handling complex backend operations efficiently. Utilizing Laravel for SSR allowed us to preserve the SEO gains the site had achieved over the years and ensured a seamless transition in search engine visibility. The entire process and rationale behind choosing Laravel over Node.js for SSR, along with its benefits for SEO in an SPA context, are further explored in a detailed discussion in my previous article: <a href="https://medium.com/@hosnyben/right-approach-for-seo-vue-vite-spa-with-server-side-rendering-vs-laravel-with-vite-vue-0bf4a2d018dc"><em>“Right Approach for SEO: Vue/Vite SPA with Server-Side Rendering vs. Laravel with Vite/Vue”</em></a>.</p><h4>Optimizing Google PageSpeed Insights</h4><p><strong>Challenge:</strong> Ensuring fast load times and high performance on Google PageSpeed Insights, crucial for both user experience and SEO.</p><p><strong>Solution:</strong> We implemented <a href="https://laravel.com/docs/11.x/cache"><strong>Laravel’s caching</strong></a> mechanisms, strategically clearing cache upon data updates to ensure content freshness without sacrificing performance.</p><h4>Data Migration</h4><p><strong>Challenge:</strong> Migrating data from an established WordPress site to a new Laravel system posed significant technical challenges. The original site had accumulated a diverse array of data over seven years, including detailed information about bookings, customer interactions, and content, all of which needed to be accurately and securely transferred to the new system.</p><p><strong>Solution:</strong> To facilitate a secure and efficient data migration process, I developed a REST API within the existing WordPress framework. This API was designed to output data in JSON format via a secured GET request, ensuring that data extraction met high security standards and prevented unauthorized access during the migration phase. Utilizing the REST API, I could systematically export data such as project details, reservation information, and user profiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*oDVS6yEOddUqWTzDXKniLg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*PwgVIB178c7_QcEi60YsOw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*eNA18PYEeFDV3o2KlIU_UQ.jpeg" /><figcaption>Migration of Categories, Projects and Reservations</figcaption></figure><p>For the data ingestion into the Laravel system, I utilized Guzzle, a PHP HTTP client, to perform GET requests to the WordPress REST API. This method allowed for the controlled retrieval of data in a structured format. Once the data was fetched, I wrote a series of Laravel console commands responsible for parsing this data and populating the Laravel models. Each piece of data was carefully mapped to its corresponding model in the Laravel database, following the pre-defined schema we set up during the system redesign phase. This process ensured that all data from the WordPress site was accurately replicated in the new Laravel system, maintaining data integrity and continuity of operations. Through this methodical approach, we successfully migrated all critical data, enabling a smooth transition to the new platform without data loss or operational disruptions.</p><h4>Creating a Partner Interface</h4><p><strong>Challenge:</strong> Developing a multi-tier access system for different stakeholders such as agents, projects managers, and transporters. Instead of the famous wordpress dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*PrYzUuEaqEU3kOYTHseAgA.jpeg" /><figcaption>The partner interface.</figcaption></figure><p><strong>Solution: </strong>Each user type received customized views relevant to their role, facilitated by a <strong>Vue/Vite SPA</strong>. For instance, transporters could see all relevant reservations, while project managers viewed only those within their purview.</p><h4>Building a Comprehensive CMS Dashboard</h4><p><strong>Challenge:</strong> Administering an extensive array of content types and user roles through a unified interface.</p><p><strong>Solution:</strong> <a href="https://nova.laravel.com/"><strong>Laravel Nova</strong></a> served as the base for the CMS, supplemented with custom fields tailored to manage specific needs like project categories, enhancing administrative efficiency.</p><h4>Optimizing Search Capabilities</h4><p><strong>Challenge:</strong> Efficiently handling search queries across a diverse set of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VvN3IiYRuEd3U38IZs57w.png" /></figure><p><strong>Solution: </strong><a href="https://www.meilisearch.com/"><strong>Meilisearch</strong></a> was integrated via <a href="https://laravel.com/docs/11.x/scout"><strong>Laravel Scout</strong></a>, providing a powerful and flexible search engine that could handle the site’s complex querying needs quickly and effectively.</p><h4>Addressing Design Limitations</h4><p><strong>Challenge: </strong>Overcoming my lack of professional design skills to produce an aesthetically pleasing and functional site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rbBJj0oAfuCgHSCO3OuJQ.png" /></figure><p><strong>Solution:</strong> <a href="https://tailwindui.com/">TailwindUI components</a> were employed to design the site and partner interfaces, providing a library of pre-designed elements that ensured a high-quality user interface despite limited design expertise.</p><h4>Finally,</h4><p>The migration of a mature <strong>WordPress</strong> site to a <strong>Laravel-based system</strong> is a complex but rewarding endeavor that enhances scalability, performance, and user experience. Through careful planning and the strategic use of modern development practices and tools, the project not only met but exceeded the original capabilities of the website, setting a new standard for future developments.</p><p>Published in LinkedIn : <a href="https://www.linkedin.com/newsletters/quick-reads-for-developers-7054820186092101632/">https://www.linkedin.com/newsletters/quick-reads-for-developers-7054820186092101632/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9f11542fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Right Approach for SEO: Vue/Vite SPA with Server-Side Rendering vs. Laravel with Vite/Vue]]></title>
            <link>https://medium.com/@hosnyben/right-approach-for-seo-vue-vite-spa-with-server-side-rendering-vs-laravel-with-vite-vue-0bf4a2d018dc?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bf4a2d018dc</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 00:09:46 GMT</pubDate>
            <atom:updated>2024-04-12T00:09:46.294Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to developing a modern web application with a focus on <strong>Search Engine Optimization (SEO)</strong>, developers often find themselves at a crossroads, choosing between a <a href="https://vuejs.org/guide/scaling-up/ssr.html"><strong>Vue/Vite Single Page Application (SPA) with server rendering</strong></a> features, or a traditional <a href="https://laravel.com/docs/11.x/vite#blade-processing-static-assets"><strong>Laravel framework utilizing Vite/Vue for asset bundling</strong></a>. Each approach has distinct advantages and potential drawbacks, particularly in how they handle SEO, a critical factor in the visibility and success of any web application. This article explores both options to help developers make an informed decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBo-wtxrCPQ3xANnvzaYZw.jpeg" /><figcaption>Vite — Vue — Laravel — NodeJS</figcaption></figure><h4>Vue/Vite SPA with Server-Side Rendering</h4><p>A Vue/Vite SPA is enticing due to its modern architecture and the flexibility it offers. Using Vue.js, a progressive JavaScript framework, alongside Vite, a newer, faster bundler and development environment, can significantly enhance the development experience and performance of applications. However, SPAs traditionally struggle with SEO since search engines may not effectively crawl JavaScript-generated content. This is where server-side rendering (SSR) becomes valuable. SSR renders the Vue components on the server before sending the fully formed HTML to the client, making the content crawlable by search engine bots from the get-go.</p><p>Implementing SSR can be more complex with a Vue/Vite setup, but frameworks like <a href="https://nuxt.com/"><strong>Nuxt.js</strong></a> offer streamlined ways to achieve SSR with Vue.js. This setup not only boosts SEO but also improves the initial load time and user experience by serving fully rendered content to users.</p><h4>Laravel with Vite/Vue</h4><p>On the other side, Laravel, a robust PHP framework, offers a more traditional approach to web development. By integrating Vue.js through Vite within Laravel, developers can leverage Laravel’s powerful features for routing, controllers, and models, while still benefiting from the reactive components of Vue.js. Laravel’s server-side rendering is intrinsic, given its PHP roots, which means content is inherently SEO-friendly as it is already server-rendered.</p><p>The integration of Vite with Laravel for managing Vue assets introduces a modern toolchain that enhances asset loading speeds and optimizes delivery for production. This combination can be particularly powerful for applications requiring complex backend functionalities with a dynamic frontend but still need good SEO out of the box.</p><h4>SEO Considerations</h4><p>The choice between these two approaches often boils down to specific SEO needs. Vue/Vite SPAs with SSR can be very SEO-friendly when configured correctly, potentially equaling the SEO performance of a Laravel setup. However, this might require additional configuration and setup, such as pre-rendering or configuring a Nuxt.js server.</p><p>Laravel with Vite/Vue, meanwhile, offers a more straightforward setup for SEO, since the server-rendered pages are more naturally indexed by search engines. This can be a significant advantage for applications where SEO is a priority from the outset, reducing the need for additional configurations.</p><h4>Development Experience and Performance</h4><p>Both setups propose unique advantages in terms of development experience and performance. Vue/Vite with SSR is cutting-edge, offering faster reloads and a more modular development experience. Laravel with Vue, while more traditional, provides a robust, full-stack development environment that many developers find easier to scale and maintain.</p><h4>Conclusion</h4><p>The decision between a Vue/Vite SPA with SSR and Laravel with Vite/Vue depends largely on the project requirements, developer expertise, and specific SEO needs. If you prioritize a modern, fast frontend with potentially complex states and are prepared to handle the intricacies of SSR for SEO, a Vue/Vite SPA might be the way to go. Conversely, if you prefer a more straightforward, robust server-side solution with less configuration for good SEO performance, Laravel with Vue and Vite is an excellent choice. In either scenario, understanding the trade-offs and benefits is key to choosing the right framework for your project’s success.</p><p>Good luck :)</p><p>LinkedIn : <a href="https://www.linkedin.com/pulse/right-approach-seo-vuevite-spa-server-side-rendering-vs-benabid-p2z8e">https://www.linkedin.com/pulse/right-approach-seo-vuevite-spa-server-side-rendering-vs-benabid-p2z8e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bf4a2d018dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Crucial Role of Internal Documentation in Streamlining Developer Onboarding]]></title>
            <link>https://medium.com/@hosnyben/the-crucial-role-of-internal-documentation-in-streamlining-developer-onboarding-6caaf1695c7a?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/6caaf1695c7a</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[team-leader]]></category>
            <category><![CDATA[wiki]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 04:36:59 GMT</pubDate>
            <atom:updated>2023-08-15T04:37:34.403Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of software development, effective communication and collaboration are paramount to success. One of the most powerful tools at a development team’s disposal is internal documentation. This often-overlooked resource plays a pivotal role in onboarding new developers, ensuring a seamless transition, and enhancing overall team efficiency. Among the various tools available for creating internal documentation, Wiki.js, a self-hosted wiki platform, stands out as a valuable choice. In this article, we’ll delve into why internal documentation is crucial and how Wiki.js can be a game-changer, while also exploring the possibility of even stronger alternatives.</p><p><strong>The Importance of Internal Documentation</strong></p><p>Internal documentation, simply put, is a set of documents created by a development team for its own use. It serves as a knowledge repository that captures everything from code standards, design principles, and architecture decisions to troubleshooting guides, best practices, and common pitfalls. The benefits of internal documentation are multifaceted:</p><ol><li><strong>Smooth Onboarding</strong>: One of the most significant advantages is the streamlined onboarding of new developers. New team members can quickly get up to speed by referring to comprehensive documentation, reducing the time spent bombarding colleagues with questions and concerns.</li><li><strong>Consistency and Standardization</strong>: Documentation ensures consistency in coding practices and design choices. This fosters a unified approach within the team, reducing errors and misunderstandings caused by differing interpretations of standards.</li><li><strong>Knowledge Sharing</strong>: Valuable insights and experiences are documented and shared, preventing knowledge silos. This enables the team to collectively learn from past successes and failures.</li><li><strong>Remote Collaboration</strong>: In today’s distributed work environments, well-documented processes and guidelines are crucial for effective remote collaboration. Documentation bridges geographical gaps by providing a centralized source of information.</li><li><strong>Continuity</strong>: Team members come and go, but documentation remains. It ensures that institutional knowledge isn’t lost when someone leaves the team, preventing disruptions.</li></ol><h3>Introducing Wiki.js for Internal Documentation</h3><p>Wiki.js is a versatile and user-friendly self-hosted wiki platform that offers an ideal solution for creating and managing internal documentation. Its features align well with the needs of development teams:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaVgfaQbAvEljmIkKxzMBw.png" /><figcaption>Homepage of https://js.wiki</figcaption></figure><ol><li><strong>Ease of Use</strong>: Wiki.js features a simple and intuitive interface that allows team members to easily create and edit documentation without the need for technical expertise.</li><li><strong>Rich Formatting</strong>: It supports various formatting options, including Markdown and WYSIWYG editing, making it convenient for both developers and non-developers to contribute.</li><li><strong>Version Control</strong>: Wiki.js provides version history and tracking, allowing for revisions and collaboration without the risk of losing previous content.</li><li><strong>Searchability</strong>: With a robust search functionality, team members can quickly locate the information they need, saving valuable time.</li><li><strong>Permissions and Access Control</strong>: Wiki.js allows you to define user roles and permissions, ensuring that sensitive information remains accessible only to authorized individuals.</li></ol><h3>Exploring Stronger Alternatives</h3><ol><li><strong>Confluence</strong>: A widely-used platform with advanced features, Confluence offers a plethora of tools for documentation, collaboration, and knowledge sharing.</li><li><strong>Notion</strong>: Known for its flexibility and ease of use, Notion combines documentation, task management, and collaboration in one platform.</li><li><strong>GitBook</strong>: A platform focused on writing and hosting documentation, GitBook seamlessly integrates with version control systems.</li></ol><p>While Wiki.js offers a robust solution, exploring alternatives is always beneficial. Some other notable options for internal documentation include:</p><p>In the end, In the world of software development, where efficiency and collaboration are paramount, internal documentation serves as the backbone of effective teamwork. By streamlining onboarding, enhancing knowledge sharing, and ensuring consistency, documentation significantly boosts a team’s productivity. Wiki.js, with its user-friendly interface and comprehensive features, emerges as an excellent choice for creating and maintaining internal documentation. However, exploring alternatives like Confluence, Notion, and GitBook can also offer additional benefits. So, if you’re looking to bolster your team’s efficiency, start investing in internal documentation today and consider which tool best suits your team’s needs. Your future developers will thank you for it.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/crucial-role-internal-documentation-streamlining-housni-benabid/"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6caaf1695c7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps Showdown: Jenkins vs. GitLab CI/CD — Unveiling the Ultimate Continious Integration Clash]]></title>
            <link>https://medium.com/@hosnyben/devops-showdown-jenkins-vs-gitlab-ci-cd-unveiling-the-ultimate-continious-integration-clash-e43aafdf7f16?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43aafdf7f16</guid>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 14:17:13 GMT</pubDate>
            <atom:updated>2023-08-09T14:18:44.159Z</atom:updated>
            <content:encoded><![CDATA[<h3>DevOps Showdown: Jenkins vs. GitLab CI/CD — Unveiling the Ultimate Continious Integration Clash</h3><p>In the world of modern software development, Continuous Integration and Continuous Deployment (CI/CD) have become integral practices for ensuring efficient, reliable, and rapid delivery of software applications. Two popular players in this arena are Jenkins and GitLab CI. In this article, we will delve into the features, strengths, and weaknesses of both tools, presenting a comprehensive comparison to help you make an informed decision about which tool suits your development needs best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6_FK-gDq82SARA4FE5r1A.png" /><figcaption>Image Source : <a href="https://medium.com/notify-events/gitlab-vs-jenkins-the-battle-for-continuous-delivery-supremacy-in-2023-cd54774b976f">https://medium.com/notify-events/gitlab-vs-jenkins-the-battle-for-continuous-delivery-supremacy-in-2023-cd54774b976f</a></figcaption></figure><h3>Jenkins: The Veteran Warrior</h3><p>Jenkins, an open-source automation server, has been a staple in the CI/CD ecosystem for quite some time. With a vast array of plugins and extensions, Jenkins offers unparalleled flexibility in configuring pipelines and automating workflows.</p><h3>Features of Jenkins</h3><ol><li>Plugin Ecosystem: Jenkins boasts a massive collection of plugins that cater to almost every requirement. This extensive plugin support allows you to customize your CI/CD pipelines to match your specific needs.</li><li>Wide Community Support: Being one of the earliest CI/CD tools, Jenkins has a large and active community. This means you can easily find solutions to common issues and share experiences with fellow developers.</li><li>Flexibility: Jenkins allows you to define pipelines as code, giving you the power to version control and maintain your build processes alongside your application code.</li></ol><p>However, Jenkins also has its drawbacks:</p><ol><li>Steep Learning Curve: The multitude of options and configurations can make Jenkins overwhelming for beginners, often resulting in a steep learning curve.</li><li>Maintenance Overhead: Managing Jenkins servers, updating plugins, and maintaining security can be a demanding task that requires dedicated resources.</li></ol><h3>GitLab CI: The All-in-One Contender</h3><p>GitLab CI is part of the GitLab platform, an integrated solution that covers not only version control but also CI/CD and other DevOps tools. This tight integration offers several advantages.</p><h3>Features of GitLab CI</h3><ol><li>Integrated Platform: GitLab CI is deeply integrated into the GitLab repository, providing a seamless experience from code writing to deployment. This integration streamlines workflows and reduces the need for external tools.</li><li>Simple Configuration: GitLab CI uses a .gitlab-ci.yml file to define pipelines. The declarative syntax is relatively easy to grasp, making it simpler for developers to set up and manage pipelines.</li><li>Containerization: GitLab CI embraces containerization, allowing you to define pipelines using Docker images. This ensures consistent environments across development, testing, and deployment stages.</li></ol><p>On the flip side:</p><ol><li>Limited Plugin Ecosystem: While GitLab CI offers a decent set of features out of the box, its plugin ecosystem might not be as extensive as Jenkins’, which could pose limitations for specific use cases.</li><li>Tied to GitLab: While the GitLab ecosystem is excellent for projects hosted on GitLab, it might not be as suitable for projects hosted elsewhere.</li></ol><h3>The Verdict</h3><p>Choosing between Jenkins and GitLab CI depends on your team’s requirements, familiarity with the tools, and the level of integration you desire.</p><p>If you value a battle-hardened tool with an extensive plugin ecosystem and don’t mind a steeper learning curve, Jenkins might be the right choice for you.</p><p>On the other hand, if you’re seeking an integrated solution with simpler configuration, better containerization support, and are already using GitLab, GitLab CI could be a more fitting option.</p><p>In conclusion, the battle between Jenkins and GitLab CI isn’t a matter of one being definitively better than the other. Instead, it’s about selecting the tool that aligns with your development philosophy, workflow, and project requirements.</p><p>No matter which tool you choose, both Jenkins and GitLab CI play crucial roles in modern CI/CD pipelines, helping developers ship code faster and more reliably than ever before.</p><p>Remember, the ultimate victory lies in delivering high-quality software efficiently, and both these tools are strong allies in that quest.</p><p><em>Originally Published in my </em><a href="https://www.linkedin.com/pulse/devops-showdown-jenkins-vs-gitlab-cicd-unveiling-ultimate-benabid/"><em>LinkedIn Newsletter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43aafdf7f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Docker for developers: A Friendly Guide to Dockerising Your Project and Saving Storage…]]></title>
            <link>https://medium.com/@hosnyben/mastering-docker-for-developers-a-friendly-guide-to-dockerising-your-project-and-saving-storage-78ce376054a?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ce376054a</guid>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[tech-lead]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Fri, 05 May 2023 10:12:15 GMT</pubDate>
            <atom:updated>2023-05-05T10:12:15.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Docker for developers: A Friendly Guide to Dockerising Your Project and Saving Storage with Efficient Dockerfiles</h3><p>Docker has taken the development world by storm, offering an innovative way to create, deploy, and run applications using containers. These containers allow for easy sharing and distribution of applications, while ensuring consistent and reproducible environments. In this friendly guide, we will discuss the best practices for dockerising a project, emphasizing the importance of writing efficient Dockerfiles to save storage consumption when building new images. Let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DDeA9eDozIZ4Zeq4NNR0A.png" /></figure><p><strong>1- Know your project inside and out</strong><br>Before you begin dockerising your project, make sure you have a thorough understanding of the project’s structure and its dependencies. This knowledge is key to creating a Dockerfile that accurately represents the application’s requirements and minimizes the introduction of unnecessary layers in the image.</p><p><strong>2- Select the perfect base image</strong><br>Choosing the right base image is essential for an efficient Dockerfile. Aim for a minimal base image that includes only the core components needed for your application. Official images provided by software vendors and the community, such as Alpine Linux, are often an excellent starting point.</p><p><strong>3- Embrace multi-stage builds</strong><br>Multi-stage builds enable you to create multiple intermediate images during the build process, each serving a specific purpose. By utilizing this technique, you can keep the final image small and clean, as only the required components from the intermediate images are included in the final output.</p><p><strong>4- Utilize a <em>.dockerignore</em> file</strong><br>To prevent unnecessary files from being included in your Docker image, create a <em>.dockerignore</em> file. This file functions similarly to a <em>.gitignore</em> file, allowing you to specify files and directories that should be excluded from the build context. Excluding unnecessary files not only reduces the size of your Docker image but also speeds up the build process.</p><p><strong>5- Optimize your Dockerfile</strong><br>An optimized Dockerfile is key to reducing storage consumption. Group related instructions together, and use Dockerfile caching intelligently to minimize the number of layers in the final image. Also, make sure to clean up temporary files and remove unused packages to keep your image size as small as possible.</p><p>Finally, dockerising a project requires careful planning and attention to detail. By following these best practices and focusing on writing efficient Dockerfiles, you can save storage space and enjoy a smooth, streamlined containerization experience. <em>Happy Dockerising!</em></p><p><em>Originally Published in my </em><a href="https://www.linkedin.com/pulse/mastering-docker-developers-friendly-guide-your-project-benabid/"><em>LinkedIn Newsletter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ce376054a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Collaboration: How Contributing to Open Source Projects and Assisting Peers Can Boost…]]></title>
            <link>https://medium.com/@hosnyben/the-power-of-collaboration-how-contributing-to-open-source-projects-and-assisting-peers-can-boost-c0f2cee09613?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0f2cee09613</guid>
            <category><![CDATA[contribution]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 09:54:07 GMT</pubDate>
            <atom:updated>2023-04-27T09:54:07.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Power of Collaboration: How Contributing to Open Source Projects and Assisting Peers Can Boost Your Web Development &amp; Software Engineering Career</h3><p><em>I genuinely regret not embracing the collaborative nature of open source projects and offering assistance on platforms like Stack Overflow in my younger years. I now realize how these experiences could have significantly enriched my skill set, expanded my network, and bolstered my professional profile.</em></p><p>In the rapidly evolving world of web development and software engineering, it’s easy for individuals to feel overwhelmed and isolated. However, playing solo is not the best approach in this industry. Collaborative learning and contributing to open source projects have proven to be essential for both personal growth and professional development. This article explores the benefits of active participation in open source projects, providing assistance on platforms like Stack Overflow, and how these activities can contribute to building a strong profile that will be attractive to recruiters.</p><h3>The Benefits of Contributing to Open Source Projects</h3><ol><li>Skill Development: By actively participating in open source projects, web developers and software engineers can improve their coding and problem-solving skills. They get the opportunity to work with different technologies, programming languages, and frameworks, expanding their knowledge base and staying current with industry trends.</li><li>Networking: Open source projects bring together like-minded professionals from all over the world. By collaborating on these projects, individuals can build connections with other professionals, which can lead to new job opportunities, mentorship, and long-lasting friendships.</li><li>Portfolio Enhancement: A strong portfolio is essential for standing out in the competitive job market. By contributing to open source projects, developers can showcase their skills and expertise, making their profile more appealing to potential employers.</li><li>Personal Branding: Open source contributions help developers establish themselves as experts in their field. This not only boosts their credibility but also increases their visibility in the industry.</li></ol><h3>The Importance of Providing Assistance on Platforms like Stack Overflow</h3><ol><li>Knowledge Sharing: By answering questions and providing assistance to peers on platforms like Stack Overflow, web developers and software engineers can solidify their understanding of complex concepts. This allows them to keep their skills sharp and up-to-date.</li><li>Reputation Building: Active participation on forums like Stack Overflow can help individuals build a positive reputation within the community. This can lead to increased visibility and credibility, which are crucial for career growth.</li><li>Problem-solving: Assisting others with their technical challenges helps developers and engineers hone their problem-solving skills. This is an essential ability in the ever-changing world of technology.</li><li>Giving Back: Contributing to the community by helping others not only feels good but also fosters a sense of belonging and camaraderie within the industry.</li></ol><p>Finally, participating in open source projects and offering assistance on platforms like Stack Overflow can be immensely beneficial for web developers and software engineers. These activities promote skill development, networking, portfolio enhancement, and personal branding, all of which are critical for building a strong profile that appeals to recruiters. By embracing collaboration and continuous learning, individuals can ensure a successful and fulfilling career in the competitive world of technology.</p><p><em>Originally Published in my </em><a href="https://www.linkedin.com/pulse/power-collaboration-how-contributing-open-source-projects-benabid/"><em>LinkedIn Newsletter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0f2cee09613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web 3.0: The playground for fearless front-end developers.]]></title>
            <link>https://medium.com/@hosnyben/web-3-0-the-playground-for-fearless-front-end-developers-2e8e7af09344?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8e7af09344</guid>
            <category><![CDATA[web3-0]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 02:44:49 GMT</pubDate>
            <atom:updated>2023-04-22T02:44:49.773Z</atom:updated>
            <content:encoded><![CDATA[<p>Web development is an ever-evolving field. As the internet has grown and changed over the years, so too have the tools and technologies used by developers. Today, we stand on the brink of a new era: the age of Web 3.0. This new iteration of the web promises to be more decentralized, more secure, and more open than anything that has come before. But what does that mean for front-end developers, and is it easy for them to make the move to Web 3.0?</p><p>Let’s start by talking about what we mean by “front-end developer.” Essentially, these are the people who make websites look good and feel great to use. They’re the ones who take care of the HTML, CSS, and JavaScript that power the user interface of every website out there. They’re responsible for making sure everything is responsive and intuitive, and that users can interact with the site in a way that feels natural.</p><p>So, what does Web 3.0 have to offer front-end developers? Well, quite a lot, actually. At its core, Web 3.0 is about decentralization. It’s about creating a web that isn’t owned and controlled by a few big players, but rather by the users themselves. This is made possible through technologies like blockchain, which provide a secure and transparent way to store and share data.</p><p>For front-end developers, this means learning new tools and technologies. Blockchain, for example, is a whole new world that requires a different way of thinking about data storage and management. But at the same time, many of the skills that front-end developers already have will be valuable in Web 3.0. After all, creating a good user interface is just as important in a decentralized app as it is on a traditional website.</p><p>So, is it easy for front-end developers to make the switch to Web 3.0? Well, that depends on the individual. There’s no denying that there will be a learning curve, and that some developers will find it easier than others. But there are plenty of resources out there to help, from online tutorials to developer communities. And the good news is that as Web 3.0 becomes more mainstream, more and more tools and frameworks will become available to make the transition smoother.</p><p>But beyond the practical considerations, there’s another reason why front-end developers might want to make the move to Web 3.0: it’s exciting! This is a whole new frontier, with new problems to solve and new possibilities to explore. For developers who are looking for a challenge and who want to be on the cutting edge of technology, Web 3.0 is an incredible opportunity.</p><p>Of course, it’s worth remembering that Web 3.0 is still in its early stages. There’s a lot that we don’t know yet, and there will be bumps in the road along the way. But for front-end developers who are up for the challenge, there’s no better time to start exploring this new world. As the web continues to evolve, those who are willing to adapt and learn will be the ones who thrive. And who knows? You might just be one of the people who helps shape the future of the internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8e7af09344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is it time to start using Github Copilot in our daily basis dev jobs ?]]></title>
            <link>https://medium.com/@hosnyben/is-it-time-to-start-using-github-copilot-in-our-daily-basis-dev-jobs-a688010b11d9?source=rss-ea15e594f595------2</link>
            <guid isPermaLink="false">https://medium.com/p/a688010b11d9</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Housni BENABID]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 20:22:15 GMT</pubDate>
            <atom:updated>2023-01-25T20:26:39.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is it time to start using Github Copilot in our coding routine ?</h3><p><em>Evaluating the Adoption of GitHub Copilot in Daily Development Operations</em></p><p><strong>GitHub Copilot</strong> is a new solution from GitHub that aims to make code development faster and more efficient by providing developers with contextually-aware code suggestions. The tool is based on machine learning and uses deep learning models to analyze the codebase and suggest code snippets and suggestions based on the context of the current file and the developer’s work history.</p><p>One of the key features of <strong>GitHub Copilot</strong> is its ability to understand the developer’s intent. For example, if a developer is working on a feature that involves updating a database, Copilot will suggest code snippets and suggestions related to database operations, rather than suggesting code snippets for working with UI elements.</p><p>Another important feature of Copilot is its ability to suggest code snippets based on the developer’s work history. By analyzing the code that the developer has written in the past, Copilot can suggest code snippets and suggestions that are most relevant to the developer’s current task. This helps to reduce the time and effort required to write code, as the developer does not have to spend time searching for the right code snippets.</p><p><strong>GitHub Copilot</strong> also provides developers with a way to quickly navigate their codebase. The tool includes a code search feature that allows developers to search for specific code snippets or functions within their codebase, making it easy to find the code they need.</p><p>Overall, <strong>GitHub Copilot</strong> is a powerful tool that can help developers to write code faster and more efficiently. It is particularly useful for developers who work on large codebases or who need to frequently switch between different projects. However, as with any machine learning model, the suggestions may not always be accurate or relevant, so developers should use their own judgement before integrating Copilot’s suggestions.</p><p>In conclusion,<strong> GitHub Copilot</strong> is a valuable addition to the toolkit of any developer working on large or complex codebases. It can help to speed up the development process and reduce the time and effort required to write code, while also providing developers with a powerful code search feature to quickly navigate their codebase. While it may not always be accurate, it can help developers to write code faster and more efficiently, and it is worth trying it out to see if it can help to improve your workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a688010b11d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>