<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Spriggan</title>
<subtitle>Where technology meets nature - cybersecurity insights, code, and forest adventures</subtitle>
<link href="https://spriggansecurity.com/"/>
<link rel="self" href="https://spriggansecurity.com/feed.xml"/>
<id>https://spriggansecurity.com/</id>
<updated>2025-12-14T00:00:00.000Z</updated>
<author><name>Spriggan</name></author>
<entry>
<title>Artifact Based Docker Deployments</title>
<link href="https://spriggansecurity.com/blog/artifact-based-docker-deployments/"/>
<id>https://spriggansecurity.com/blog/artifact-based-docker-deployments/</id>
<published>2025-12-14T00:00:00.000Z</published>
<updated>2025-12-14T00:00:00.000Z</updated>
<category term="docker"/><category term="deployment"/><category term="ci"/><category term="cd"/><category term="ci/cd"/>
<summary>Stop building on servers.</summary>
<content type="html">&lt;h1&gt;Immutable Artifact Deployments&lt;/h1&gt;
&lt;p&gt;Stop building on servers.&lt;/p&gt;
&lt;p&gt;There&amp;#39;s a cleaner way to deploy containerized applications. Instead of pulling code to a server and building it there, wasting cycles and sanity, we build Docker images once in CI/CD and ship immutable artifacts to production.&lt;/p&gt;
&lt;p&gt;This eliminates an entire class of deployment failures. If the build passes in CI, it runs in production because they&amp;#39;re literally the same artifact. No more &amp;quot;it worked in CI but failed on the server during npm install&amp;quot; nightmares at 3am. (I don&amp;#39;t actually stay up that late anymore).&lt;/p&gt;
&lt;p&gt;One of the unique challenges that may come up is the difference between compiling something like a TSed backend, and putting it in a container, versus static code like Angular. We are going to explore what it may require to get an Angular Container shipped. &lt;/p&gt;
&lt;h2&gt;The Core Concept&lt;/h2&gt;
&lt;p&gt;Traditional deployments transfer source code to a server, then build it. This creates problems:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Server resources consumed by build processes&lt;/li&gt;
&lt;li&gt;Risk of deploying broken code that fails to build in production&lt;/li&gt;
&lt;li&gt;Stale files lingering unless explicitly deleted&lt;/li&gt;
&lt;li&gt;Different build outputs between environments&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The fix: build Docker images in GitHub Actions, push them to a container registry, then pull and run them on the server. One build, deploy anywhere.&lt;/p&gt;
&lt;h2&gt;Architecture Overview&lt;/h2&gt;
&lt;p&gt;Three phases:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Build Phase&lt;/strong&gt; (GitHub Actions)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Compile application into Docker images&lt;/li&gt;
&lt;li&gt;Tag with commit SHA and environment&lt;/li&gt;
&lt;li&gt;Push to GitHub Container Registry (GHCR)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;2. Sync Phase&lt;/strong&gt; (GitHub Actions → Server)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Transfer only deployment manifests via rsync&lt;/li&gt;
&lt;li&gt;Use SSH for secure server access&lt;/li&gt;
&lt;li&gt;Minimal file sync, preserving directory structure&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;3. Deploy Phase&lt;/strong&gt; (Server)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Pull pre-built images from registry&lt;/li&gt;
&lt;li&gt;Recreate containers with new images&lt;/li&gt;
&lt;li&gt;Clean up old resources&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Setting Up the Pipeline&lt;/h2&gt;
&lt;h3&gt;The Reusable Workflow&lt;/h3&gt;
&lt;p&gt;Create &lt;code&gt;.github/workflows/deploy.yml&lt;/code&gt;. This is the core deployment logic that multiple environments will call:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Deployment&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Pipeline&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;on:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;workflow_call:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;inputs:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;required:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;type:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;string&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;secrets:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;SSH_PRIVATE_KEY:&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;required:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;jobs:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;deploy:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Deploy&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;inputs.environment&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;inputs.environment&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;runs-on:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;ubuntu-latest&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;steps:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;actions/checkout@v4&lt;/span&gt;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;# Log into GHCR using the automatic GITHUB_TOKEN&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# This token is scoped to the repository and automatically available&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Log&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;GHCR&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;docker/login-action@v2&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;registry:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;ghcr.io&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;username:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;github.actor&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;password:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;secrets.GITHUB_TOKEN&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;# Build the Docker image and push with two tags:&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 1. Commit SHA for immutable reference&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 2. Environment-latest for convenience&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Build&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Push&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Image&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;docker/build-push-action@v4&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;context:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;./client&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;push:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;tags:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;|
            ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}-client:${{ github.sha }}
            ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}-client:${{ inputs.environment }}-latest
&lt;/span&gt;      
      &lt;span class=&quot;hljs-comment&quot;&gt;# Load SSH private key into the SSH agent&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# This allows rsync and ssh commands to authenticate&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Set&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;up&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;SSH&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;webfactory/ssh-agent@v0.5.3&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;ssh-private-key:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;secrets.SSH_PRIVATE_KEY&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;# Two-step deployment:&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 1. Rsync deployment files to server&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 2. SSH in and execute the deploy script&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Update&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Server&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Deployment&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;env:&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;SERVER_LOGIN:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;vars.SSH_USER&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}@${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;vars.TARGET_SERVER&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;DEPLOY_DIR:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;vars.DEPLOY_DIR&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;run:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;|
          # Sync only files listed in deploy-manifest.txt
          # This prevents transferring source code or unnecessary files
          rsync -avz --files-from=deploy-manifest.txt \
            -e &amp;quot;ssh -o StrictHostKeyChecking=no&amp;quot; \
            ./ ${{ env.SERVER_LOGIN }}:${{ env.DEPLOY_DIR }}/
&lt;/span&gt;          
          &lt;span class=&quot;hljs-comment&quot;&gt;# SSH to server and:&lt;/span&gt;
          &lt;span class=&quot;hljs-comment&quot;&gt;# 1. Login to GHCR (forwarding the token)&lt;/span&gt;
          &lt;span class=&quot;hljs-comment&quot;&gt;# 2. Run deploy.sh with the commit SHA as TAG&lt;/span&gt;
          &lt;span class=&quot;hljs-comment&quot;&gt;# 3. Logout for security cleanup&lt;/span&gt;
          &lt;span class=&quot;hljs-string&quot;&gt;ssh&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;-o&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;StrictHostKeyChecking=no&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;env.SERVER_LOGIN&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;
            cd $&lt;span class=&quot;hljs-template-variable&quot;&gt;{{ env.DEPLOY_DIR }}&lt;/span&gt; &amp;amp;&amp;amp; \
            echo &amp;#x27;$&lt;span class=&quot;hljs-template-variable&quot;&gt;{{ secrets.GITHUB_TOKEN }}&lt;/span&gt;&amp;#x27; | docker login ghcr.io -u $&lt;span class=&quot;hljs-template-variable&quot;&gt;{{ github.actor }}&lt;/span&gt; --password-stdin &amp;amp;&amp;amp; \
            chmod +x deploy.sh &amp;amp;&amp;amp; \
            TAG=$&lt;span class=&quot;hljs-template-variable&quot;&gt;{{ github.sha }}&lt;/span&gt; ./deploy.sh &amp;amp;&amp;amp; \
            docker logout ghcr.io
          &amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;workflow_call&lt;/code&gt; is a pattern that lets us define deployment logic once and reuse it across multiple environments with different triggers. Dev deploys on merge to main, prod deploys on release. This is my preferred style of doing this right now, but there are a gazillion ways to trigger these workflows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;About GITHUB_TOKEN:&lt;/strong&gt; This is automatically available in workflows with read permissions. We need to explicitly grant write permissions for it to push to GHCR.&lt;/p&gt;
&lt;h3&gt;Environment-Specific Triggers&lt;/h3&gt;
&lt;p&gt;Create separate workflow files that call the reusable workflow with different triggers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dev&lt;/strong&gt; (&lt;code&gt;.github/workflows/deploy-dev.yml&lt;/code&gt;): Deploy on merge to main&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Deploy&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Development&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# Prevent concurrent deployments to dev&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# If a new push happens while deploying, cancel the old one&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;concurrency:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;group:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;deploy_dev&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;cancel-in-progress:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;on:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;push:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;branches:&lt;/span&gt; [&lt;span class=&quot;hljs-string&quot;&gt;main&lt;/span&gt;]
    &lt;span class=&quot;hljs-comment&quot;&gt;# Don&amp;#x27;t trigger on documentation changes&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;paths-ignore:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;**/*.md&amp;#x27;&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;docs/**&amp;#x27;&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;jobs:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;call-reusable:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;./.github/workflows/deploy.yml&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;dev&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;secrets:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;SSH_PRIVATE_KEY:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;secrets.SSH_PRIVATE_KEY&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Production&lt;/strong&gt; (&lt;code&gt;.github/workflows/deploy-prod.yml&lt;/code&gt;): Deploy on release&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Deploy&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Production&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;concurrency:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;group:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;deploy_prod&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;cancel-in-progress:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;  &lt;span class=&quot;hljs-comment&quot;&gt;# Don&amp;#x27;t cancel prod deployments&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;on:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;release:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;types:&lt;/span&gt; [&lt;span class=&quot;hljs-string&quot;&gt;published&lt;/span&gt;]  &lt;span class=&quot;hljs-comment&quot;&gt;# Triggers when publishing a release in GitHub&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;jobs:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;call-reusable:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;./.github/workflows/deploy.yml&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;prod&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;secrets:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;SSH_PRIVATE_KEY:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${{&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;secrets.SSH_PRIVATE_KEY&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;}}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Why separate triggers?&lt;/strong&gt; Dev gets every merge for rapid iteration. Production gets deliberate releases. Same deployment code, different cadence.&lt;/p&gt;
&lt;h2&gt;Containerizing Angular&lt;/h2&gt;
&lt;p&gt;Angular apps compile to static files. Don&amp;#39;t run &lt;code&gt;ng serve&lt;/code&gt; in production, it&amp;#39;s a development server and is not properly optimized.&lt;/p&gt;
&lt;p&gt;Multi-stage Dockerfile for Angular:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-dockerfile&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Stage 1: Build the Angular app&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;FROM&lt;/span&gt; node:&lt;span class=&quot;hljs-number&quot;&gt;20&lt;/span&gt;-alpine AS build
&lt;span class=&quot;hljs-keyword&quot;&gt;WORKDIR&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; /build&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;COPY&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; package*.json ./&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;RUN&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; npm ci  &lt;span class=&quot;hljs-comment&quot;&gt;# Use ci instead of install for reproducible builds&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;COPY&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; . .&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;RUN&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; npm run build&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# Stage 2: Serve with Caddy&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;FROM&lt;/span&gt; caddy:alpine
&lt;span class=&quot;hljs-keyword&quot;&gt;WORKDIR&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; /app&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# Copy only the built artifacts, not node_modules or source&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;COPY&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; --from=build /build/dist/your-app/browser ./www&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;EXPOSE&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;80&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# Caddy&amp;#x27;s file-server mode serves static files efficiently&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;CMD&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; [&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;caddy&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;file-server&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;--root&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/app/www&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;--listen&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:80&amp;quot;&lt;/span&gt;]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The build stage includes Node.js and all dev dependencies. The final stage contains only static files and Caddy, which is much smaller. The build artifacts are immutable; the container is just a delivery mechanism.&lt;/p&gt;
&lt;p&gt;Why the Proxy? The compiled Angular app is just static files. These need to be served over HTTP. By embedding Caddy in the container, we package everything the app needs to run. The outer Caddy proxy (defined in docker-compose) handles SSL and routing, while the inner Caddy simply serves files on port 4200.&lt;/p&gt;
&lt;p&gt;The proxy configuration in &lt;code&gt;proxy/Caddyfile&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;{$DOMAIN} {
    reverse_proxy client:&lt;span class=&quot;hljs-number&quot;&gt;4200&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Server-Side Configuration&lt;/h2&gt;
&lt;h3&gt;Docker Compose for Deployment&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;docker-compose.deploy.yml&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;services:&lt;/span&gt;
  &lt;span class=&quot;hljs-comment&quot;&gt;# Reverse proxy handling SSL and routing&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;proxy:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;image:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;caddy:alpine&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;volumes:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;./proxy/Caddyfile:/etc/caddy/Caddyfile&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;ports:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;80:80&amp;quot;&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;443:443&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DOMAIN:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;${DOMAIN}&lt;/span&gt;
  
  &lt;span class=&quot;hljs-comment&quot;&gt;# The application container&lt;/span&gt;
  &lt;span class=&quot;hljs-comment&quot;&gt;# The TAG environment variable is set by deploy.sh&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;client:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;image:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;ghcr.io/your-org/your-repo-client:${TAG}&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;expose:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;4200&lt;/span&gt;  &lt;span class=&quot;hljs-comment&quot;&gt;# Internal only, not published to host&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The proxy handles SSL termination and routing. The app container doesn&amp;#39;t know or care about HTTPS. This separation lets us update the app without touching SSL certs, and vice versa.&lt;/p&gt;
&lt;h3&gt;Deployment Script&lt;/h3&gt;
&lt;p&gt;This file is somewhat dynamic and will depend on the setup and dependencies. Typically we run this as a &amp;quot;post deploy&amp;quot; step after the github workflow has almost completed. THe purpose is to pull the images that have been built, recreates them if needed. &lt;/p&gt;
&lt;p&gt;&lt;code&gt;deploy.sh&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;#!/usr/bin/env bash&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; -eo pipefail

&lt;span class=&quot;hljs-comment&quot;&gt;# Use deploy compose file&lt;/span&gt;
docker compose -f docker-compose.deploy.yml pull
docker compose -f docker-compose.deploy.yml up -d --force-recreate
docker system prune -f

&lt;span class=&quot;hljs-built_in&quot;&gt;echo&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Deployment complete&amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;set -eo pipefail&lt;/code&gt; will exit immediately if any command fails (&lt;code&gt;-e&lt;/code&gt;), and catch failures in piped commands (&lt;code&gt;-o pipefail&lt;/code&gt;). This prevents partial deployments.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--force-recreate&lt;/code&gt; because sometimes we need to deploy the same image with different environment variables. This ensures containers are rebuilt even if the image hasn&amp;#39;t changed.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docker system prune -f&lt;/code&gt; removes all unused containers, networks, and images in one shot. More aggressive than image pruning, but keeps the system clean. The &lt;code&gt;-f&lt;/code&gt; flag skips confirmation prompts.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;note: it may be necessary to add migration code here, and its reasonable to add a check for environment variables that are required for the deployment workflow. I will often ahve caddy setup on projects and I reload caddy after I recreate and run migrations.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Deployment Manifest&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;deploy-manifest.txt&lt;/code&gt; specifies exactly which files rsync transfers:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker-compose.deploy.yml
proxy/Caddyfile
deploy.sh&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Why a manifest?&lt;/strong&gt; This is specifically for files that don&amp;#39;t get built into images. I prefere a manifest over managing this transfer in the deploy workflow. Without it, rsync transfers everything: source code, node_modules, .git history. This is wasteful and can cause permission issues. The manifest ensures only deployment files reach the server. There may be a better way to handle this that is less manual and touchy, but it works for now.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Server Setup&lt;/h2&gt;
&lt;p&gt;Prepare the server once:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Install Docker (don&amp;#x27;t use apt for this, get the latest)&lt;/span&gt;
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

&lt;span class=&quot;hljs-comment&quot;&gt;# Install Docker Compose plugin&lt;/span&gt;
apt install docker-compose-plugin -y

&lt;span class=&quot;hljs-comment&quot;&gt;# Create deployment directory&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; -p /opt/deployments
&lt;span class=&quot;hljs-built_in&quot;&gt;chown&lt;/span&gt; &lt;span class=&quot;hljs-variable&quot;&gt;$USER&lt;/span&gt;:&lt;span class=&quot;hljs-variable&quot;&gt;$USER&lt;/span&gt; /opt/deployments

&lt;span class=&quot;hljs-comment&quot;&gt;# Add SSH public key for GitHub Actions&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; -p ~/.ssh
&lt;span class=&quot;hljs-built_in&quot;&gt;echo&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;YOUR_PUBLIC_KEY&amp;quot;&lt;/span&gt; &amp;gt;&amp;gt; ~/.ssh/authorized_keys
&lt;span class=&quot;hljs-built_in&quot;&gt;chmod&lt;/span&gt; 700 ~/.ssh &amp;amp;&amp;amp; &lt;span class=&quot;hljs-built_in&quot;&gt;chmod&lt;/span&gt; 600 ~/.ssh/authorized_keys&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;note: Create a dedicated deploy user instead of using root. Add them to the docker group so they can run docker commands without sudo. This is necessary, but I like to do this in principle out of habit.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;GitHub Configuration&lt;/h2&gt;
&lt;h3&gt;Enable GHCR Write Access&lt;/h3&gt;
&lt;p&gt;Navigate to &lt;strong&gt;Settings → Actions → General → Workflow permissions&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Select &amp;quot;Read and write permissions&amp;quot;&lt;/li&gt;
&lt;li&gt;Check &amp;quot;Allow GitHub Actions to create and approve pull requests&amp;quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This grants GITHUB_TOKEN the ability to push images to GHCR. Without this, the workflow can build but not publish.&lt;/p&gt;
&lt;h3&gt;Repository Secretssss&lt;/h3&gt;
&lt;p&gt;Navigate to &lt;strong&gt;Settings → Secrets and variables → Actions → Secrets&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SSH_PRIVATE_KEY&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Generate a new SSH key pair specifically for deployments&lt;/span&gt;
ssh-keygen -t ed25519 -C &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github-actions-deploy&amp;quot;&lt;/span&gt; -f ~/.ssh/deploy_key -N &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;&amp;quot;&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# Copy the private key content (including BEGIN/END lines)&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;cat&lt;/span&gt; ~/.ssh/deploy_key

&lt;span class=&quot;hljs-comment&quot;&gt;# Add the public key to the server&amp;#x27;s authorized_keys&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;cat&lt;/span&gt; ~/.ssh/deploy_key.pub&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Paste the entire private key as the secret value. Add the public key to the server&amp;#39;s &lt;code&gt;~/.ssh/authorized_keys&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Repository Variables&lt;/h3&gt;
&lt;p&gt;Navigate to &lt;strong&gt;Settings → Secrets and variables → Actions → Variables&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;SSH_USER&lt;/code&gt;: Username for SSH connection (e.g., &lt;code&gt;deploy&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;TARGET_SERVER&lt;/code&gt;: Server IP or domain (e.g., &lt;code&gt;192.168.1.100&lt;/code&gt; or &lt;code&gt;app.example.com&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;DEPLOY_DIR&lt;/code&gt;: Deployment directory path (e.g., &lt;code&gt;/opt/deployments&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Variables vs Secrets:&lt;/strong&gt; Use variables for non-sensitive configuration. They&amp;#39;re visible in workflow logs, making debugging easier. Secrets are masked in logs and should only be used for credentials. I discovered this the hard way when I was trying to figure out why my action was failing and all the lines I was try to read about the server was redacted from the logs.&lt;/p&gt;
&lt;h2&gt;Why This Works&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Each commit produces exactly one set of images, tagged with the commit SHA, which removes ambiguity.&lt;/li&gt;
&lt;li&gt;Dev, staging, and production run identical images. Configuration differences are handled via environment variables..&lt;/li&gt;
&lt;li&gt;Change one line in docker-compose.deploy.yml or re-run the workflow with a previous commit SHA.&lt;/li&gt;
&lt;li&gt;GitHub Actions runners compile the code. This keeps servers lean and predictable.&lt;/li&gt;
&lt;li&gt;Images are built and scanned in CI before deployment. Servers never see source code, npm tokens, or build secrets.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;The Deployment Dance&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Push code to main (or publish a release)&lt;/li&gt;
&lt;li&gt;GitHub Actions builds Docker images&lt;/li&gt;
&lt;li&gt;Images pushed to GHCR with commit SHA tag&lt;/li&gt;
&lt;li&gt;Deployment files synced to server via rsync&lt;/li&gt;
&lt;li&gt;Server pulls images and recreates containers&lt;/li&gt;
&lt;li&gt;Old containers stopped, new ones started&lt;/li&gt;
&lt;li&gt;Old images cleaned up after 24 hours or in post deploy scripts&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If something breaks, the workflow fails before touching production.&lt;/p&gt;
&lt;h2&gt;Future Augmentations&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Secrets Management&lt;/strong&gt;: This example uses basic environment variables. For production, consider dotenvx for encrypted secrets in source control, or use a proper secrets manager.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Networking&lt;/strong&gt;: Replace SSH keys with Tailscale for simplified access management. No key rotation, no exposed SSH ports. [[tailscale-pulumi-implementation-guide]]&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Monitoring&lt;/strong&gt;: Add health checks to the deploy script. Poll the service after deployment and automatically rollback if it fails to respond.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Image Tags&lt;/strong&gt;: Use both SHA and environment tags. SHA tags are immutable references to specific versions. Environment tags (like &lt;code&gt;prod-latest&lt;/code&gt;) provide convenience but can move.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Multiple Services&lt;/strong&gt;: If there are multiple services (API, worker, frontend), build and push them all in parallel, then deploy them together. GitHub Actions builds make this efficient.&lt;/p&gt;
&lt;h2&gt;The Neon Lit Bottom Line&lt;/h2&gt;
&lt;p&gt;We want to build and test the same artifact between environments. Consistency is key.&lt;/p&gt;
&lt;p&gt;Servers become dumb terminals in the best way. Pull image. Run container. Predictable execution in the server racks humming somewhere dehydrating our planet.&lt;/p&gt;
&lt;p&gt;When the inevitable deployment goes haywire we can simply rollback by changing a single tag. No rebuilds, no SSH sessions with bleary eyes trying to remember which env variable was not added. The commit SHA is the contract here.&lt;/p&gt;
&lt;p&gt;The machine doesn&amp;#39;t care about our anxieties. It runs what we give it. &lt;/p&gt;
</content>
</entry>
<entry>
<title>How to Update Subnet Routes in Tailscale</title>
<link href="https://spriggansecurity.com/blog/how-to-update-subnet-routes-in-tailscale/"/>
<id>https://spriggansecurity.com/blog/how-to-update-subnet-routes-in-tailscale/</id>
<published>2025-12-14T00:00:00.000Z</published>
<updated>2025-12-14T00:00:00.000Z</updated>
<category term="tailscale"/><category term="networking"/>
<summary>When working with private VPC resources (like an AWS OpenSearch endpoint) you may find that devices on your Tailnet can’t reach them even though they’re connected to the…</summary>
<content type="html">&lt;p&gt;When working with private VPC resources (like an AWS OpenSearch endpoint) you may find that devices on your Tailnet can’t reach them even though they’re connected to the same VPC as the VPN server. The issue is often missing subnet routes.&lt;/p&gt;
&lt;p&gt;This guide walks through how to advertise and approve subnet routes in Tailscale so your devices can access private network resources.&lt;/p&gt;
&lt;p&gt;This example specifically came from me and another engineer troubleshooting our VPN connection to OpenSearch but the concepts more or less would be the same in other instances.&lt;/p&gt;
&lt;h2&gt;1. Identify the Network You Need Access To&lt;/h2&gt;
&lt;p&gt;If you can reach your target resource (e.g., OpenSearch, EC2, etc) &lt;strong&gt;from your VPN server&lt;/strong&gt; but &lt;strong&gt;not from your local machine&lt;/strong&gt;, the issue is likely subnet routing.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;VPN server can &lt;code&gt;curl&lt;/code&gt; the OpenSearch endpoint successfully.&lt;/li&gt;
&lt;li&gt;Local machine on the Tailnet cannot.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;2. Check Your VPC Subnets&lt;/h2&gt;
&lt;p&gt;Determine which CIDR blocks your environment uses.  You&amp;#39;ll have to spelunk around in aws to find these under one of the network config tabs for the resource trying to be accessed.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Production VPC:&lt;/strong&gt; &lt;code&gt;10.0.0.0/16&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Development VPC:&lt;/strong&gt; &lt;code&gt;172.30.0.0/16&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;VPN VPC:&lt;/strong&gt; &lt;code&gt;172.31.0.0/16&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You’ll need to advertise these routes from the VPN server so Tailnet clients can reach them.&lt;/p&gt;
&lt;h2&gt;3. Advertise the Required Routes&lt;/h2&gt;
&lt;p&gt;On the VPN server (already connected to your Tailnet), run:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# For production&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; tailscale &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; --advertise-routes=10.0.0.0/16

&lt;span class=&quot;hljs-comment&quot;&gt;# For VPN + Dev combined&lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; tailscale &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; --advertise-routes=172.31.0.0/16,172.30.0.0/16&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you try to advertise overlapping routes (e.g., multiple /16s covering similar space), Tailscale may report a conflict, only advertise the specific subnets you need.&lt;/p&gt;
&lt;h2&gt;4. Approve the Routes in the Tailscale Admin Console&lt;/h2&gt;
&lt;p&gt;After advertising, the routes will appear as “pending” until approved.  &lt;/p&gt;
&lt;p&gt;Go to:  &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;[Tailscale Admin Console → Machines → Your VPN Server → Routes]&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Approve each route you want other devices on the Tailnet to use.&lt;/p&gt;
&lt;p&gt;Reference: &lt;a href=&quot;https://tailscale.com/kb/1019/subnets#add-access-rules-for-the-advertised-subnet-routes&quot;&gt;Tailscale Docs – Subnet Routers&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;5. Verify Access&lt;/h2&gt;
&lt;p&gt;Once routes are approved:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Ensure your local machine is connected to the Tailnet.&lt;/li&gt;
&lt;li&gt;Try accessing the resource again&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl --location --request GET &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;https://&amp;lt;your-opensearch-endpoint&amp;gt;/profiles/_search&amp;#x27;&lt;/span&gt; \
  --header &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Content-Type: application/json&amp;#x27;&lt;/span&gt; \
  --header &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Authorization: Basic &amp;lt;your-auth-key&amp;gt;&amp;#x27;&lt;/span&gt; \
  --data &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;{ &amp;quot;size&amp;quot;: 100, &amp;quot;sort&amp;quot;: [ { &amp;quot;os_created_at&amp;quot;: &amp;quot;desc&amp;quot; } ] }&amp;#x27;&lt;/span&gt; -vvv&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the routes are set up correctly, your local machine should now connect successfully.&lt;/p&gt;
</content>
</entry>
<entry>
<title>Tailscale Pulumi Implementation Guide</title>
<link href="https://spriggansecurity.com/blog/tailscale-pulumi-implementation-guide/"/>
<id>https://spriggansecurity.com/blog/tailscale-pulumi-implementation-guide/</id>
<published>2025-12-13T00:00:00.000Z</published>
<updated>2025-12-13T00:00:00.000Z</updated>
<category term="devops"/><category term="cybersecurity"/><category term="tailscale"/>
<summary>You want to automate the deployment of VMs that will automatically join a Tailscale network on first boot. No SSH keys to distribute, no extra exposed ports, no manual…</summary>
<content type="html">&lt;h2&gt;Why infrastructure as Code for Tailscale Deployment?&lt;/h2&gt;
&lt;p&gt;You want to automate the deployment of VMs that will automatically join a Tailscale network on first boot. No SSH keys to distribute, no extra exposed ports, no manual server configuration. This guide is meant to walk you through building that with Pulumi, cloud-init, and Digital Ocean.&lt;/p&gt;
&lt;p&gt;Infrastructure as Code (IaC) is a whole bag of worms, but it does offer some distinct advantages when building and deploying software. One of the main reasons I like to use it is to prevent drift between environments. Time and time again I&amp;#39;ve had to figure out why configurations between dev/prod were behaving differently and it would be some policy, or configuration that was manually applied, or a misconfigured vpc. It&amp;#39;s hard to keep track of what engineers are doing at all times. &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reproducibility - Define infrastructure, deploy it consistently across environments. No manual configuration drift.&lt;/li&gt;
&lt;li&gt;Security by default: Embedding Tailscale into the IaC setup means every VM automatically joins the zero-trust network on first boot. No SSH keys to manage or share, no exposed ports, no additional VPN configuration.&lt;/li&gt;
&lt;li&gt;Rapid scaling: Easy to deploy 5+ of the exact same server with the same settings and configurations, and they automatically show up on the Tailscale network.&lt;/li&gt;
&lt;li&gt;Version Control: The Infrastructure as Code configuration lives in Git. Making it easy to Review changes, rollback mistakes, and have an audit trail for the networking setup. &lt;/li&gt;
&lt;li&gt;Ephemeral Auth: Tailscale auth keys are injected at deplyoment time and used only once. No long-lived creds every get stored on disk.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Getting started&lt;/h2&gt;
&lt;p&gt;This implementation uses Pulumi which is a typescript based IaC, with cloud-init to achieve as close to a zero touch Tailscale deployment on pretty much any cloud provider. For this example we are using Digital Ocean, but it is just as easy to do this on any other cloud provider like AWS.&lt;/p&gt;
&lt;p&gt;I&amp;#39;m going to walk you through how to set this up from scratch, so that you have your own version of this repo that you can customize as needed. If you would like you can also check out the version of this that&amp;#39;s been built already.&lt;/p&gt;
&lt;h3&gt;Flow&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Pulumi reads Tailscale auth key from encrypted configuration&lt;/li&gt;
&lt;li&gt;Cloud-init script generated with embedded Tailscale setup&lt;/li&gt;
&lt;li&gt;VM deployed with cloud-init user data&lt;/li&gt;
&lt;li&gt;On boot, cloud-init installs and configures Tailscale automatically&lt;/li&gt;
&lt;li&gt;VM joins the Tailscale network with specified hostname and settings&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Security Model&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;No SSH port 22 exposed to internet&lt;/li&gt;
&lt;li&gt;Only Tailscale UDP (41641) and ICMP allowed inbound&lt;/li&gt;
&lt;li&gt;SSH access exclusively through Tailscale network&lt;/li&gt;
&lt;li&gt;Auth keys stored as Pulumi secrets&lt;/li&gt;
&lt;li&gt;No persistent credentials on VMs&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2&gt;Prerequisites&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Tailscale Account&lt;/strong&gt; - Sign up at &lt;a href=&quot;https://tailscale.com&quot;&gt;tailscale.com&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;Github Account (Assume you probably have one)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pulumi CLI&lt;/strong&gt; - Install from &lt;a href=&quot;https://www.pulumi.com/docs/get-started/install/&quot;&gt;pulumi.com/docs/get-started/install&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Node.js&lt;/strong&gt; - Version 20 or later  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cloud Provider Account&lt;/strong&gt; - DigitalOcean&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Initialize project Directory&lt;/h2&gt;
&lt;h3&gt;Project Structure&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;src/
├── cloud-init.ts # Generates cloud-init YAML with Tailscale setup
├── providers/
│ ├── aws.ts # AWS EC2 implementation (placeholder)
│ └── digitalocean.ts # DigitalOcean Droplet implementation
index.ts # Main Pulumi program with provider selection&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; tailscale-pulumi &amp;amp;&amp;amp; &lt;span class=&quot;hljs-built_in&quot;&gt;cd&lt;/span&gt; tailscale-pulumi
&lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; -p src/providers&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Create a package.json&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;name&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tailscale-pulumi&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;version&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;1.0.0&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;main&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;index.ts&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;scripts&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;deploy&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;pulumi up&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;destroy&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;pulumi destroy&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;preview&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;pulumi preview&amp;quot;&lt;/span&gt;
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;dependencies&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@pulumi/digitalocean&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;^4.0.0&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@pulumi/pulumi&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;^3.0.0&amp;quot;&lt;/span&gt;
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;devDependencies&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@types/node&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;^20.19.9&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;typescript&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;^5.0.0&amp;quot;&lt;/span&gt;
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Run &lt;code&gt;npm install&lt;/code&gt; to pull down the required dependencies&lt;/p&gt;
&lt;h3&gt;Minimalist tsconfig&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;compilerOptions&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;target&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;ES2020&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;module&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;commonjs&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;moduleResolution&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;node&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;outDir&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./dist&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;strict&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;esModuleInterop&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;include&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;src/**/*&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;*.ts&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;exclude&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;node_modules&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;dist&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing fancy here. And heck it probably wont even work because Typescript is glorious like that, but I believe in you.&lt;/p&gt;
&lt;h3&gt;pulumi.yaml&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;tailscale-pulumi&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;runtime:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;nodejs&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;description:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Automated&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Tailscale&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;deployment&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;cloud-init&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;template:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;config:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;tailscale-pulumi:authkey:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;description:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Tailscale&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;auth&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;automatic&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;node&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;registration&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;secret:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;secret: true&lt;/code&gt; flag ensures the auth key is encrypted in the pulumi state file. &lt;/p&gt;
&lt;h3&gt;Building the Cloud Init Script&lt;/h3&gt;
&lt;p&gt;Cloud-init is the secret sauce to this recipe. It&amp;#39;s a standard for VM initializations that all major cloud providers support. I was stumped trying to figure out exactly the best point to inject Tailscale into server set up. But cloud init is the hook I wanted and needed. This can be set up as a more barebones script file, but to cater to the nature of this node project we are writing it in typescript.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; pulumi &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@pulumi/pulumi&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;TailscaleConfig&lt;/span&gt; {
  &lt;span class=&quot;hljs-attr&quot;&gt;authKey&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt; | pulumi.&lt;span class=&quot;hljs-property&quot;&gt;Input&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;&amp;gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;hostname&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;acceptRoutes&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;boolean&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;enableSSH&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;boolean&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;tags&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;[];
}

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;generateCloudInitUserData&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;config&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;TailscaleConfig&lt;/span&gt;&lt;/span&gt;): pulumi.&lt;span class=&quot;hljs-property&quot;&gt;Output&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;&amp;gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; pulumi.&lt;span class=&quot;hljs-title function_&quot;&gt;output&lt;/span&gt;(config.&lt;span class=&quot;hljs-property&quot;&gt;authKey&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;apply&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;authKey&lt;/span&gt; =&amp;gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// Build Tailscale command-line arguments&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; hostname = config.&lt;span class=&quot;hljs-property&quot;&gt;hostname&lt;/span&gt; ? &lt;span class=&quot;hljs-string&quot;&gt;`--hostname=&lt;span class=&quot;hljs-subst&quot;&gt;${config.hostname}&lt;/span&gt;`&lt;/span&gt; : &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;#x27;&lt;/span&gt;;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; acceptRoutes = config.&lt;span class=&quot;hljs-property&quot;&gt;acceptRoutes&lt;/span&gt; ? &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;--accept-routes&amp;#x27;&lt;/span&gt; : &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;#x27;&lt;/span&gt;;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; sshFlag = config.&lt;span class=&quot;hljs-property&quot;&gt;enableSSH&lt;/span&gt; ? &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;--ssh&amp;#x27;&lt;/span&gt; : &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;#x27;&lt;/span&gt;;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tags = config.&lt;span class=&quot;hljs-property&quot;&gt;tags&lt;/span&gt;?.&lt;span class=&quot;hljs-property&quot;&gt;length&lt;/span&gt; ? &lt;span class=&quot;hljs-string&quot;&gt;`--advertise-tags=&lt;span class=&quot;hljs-subst&quot;&gt;${config.tags.join(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;,&amp;#x27;&lt;/span&gt;)}&lt;/span&gt;`&lt;/span&gt; : &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;#x27;&lt;/span&gt;;
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tailscaleArgs = [hostname, acceptRoutes, sshFlag, tags]
      .&lt;span class=&quot;hljs-title function_&quot;&gt;filter&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;arg&lt;/span&gt; =&amp;gt;&lt;/span&gt; arg.&lt;span class=&quot;hljs-property&quot;&gt;length&lt;/span&gt; &amp;gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;)
      .&lt;span class=&quot;hljs-title function_&quot;&gt;join&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27; &amp;#x27;&lt;/span&gt;);

    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;`#cloud-config
			package_update: true
			package_upgrade: true
			
			packages:
			  - curl
			
			write_files:
			  - path: /etc/tailscale-setup.sh
			    permissions: &amp;#x27;0755&amp;#x27;
			    content: |
			      #!/bin/bash
			      set -euo pipefail
			      
			      echo &amp;quot;Installing Tailscale...&amp;quot;
			      curl -fsSL https://tailscale.com/install.sh | sh
			      
			      systemctl enable --now tailscaled
			      sleep 5
			      
			      echo &amp;quot;Connecting to Tailscale network...&amp;quot;
			      tailscale up --authkey=&lt;span class=&quot;hljs-subst&quot;&gt;${authKey}&lt;/span&gt; &lt;span class=&quot;hljs-subst&quot;&gt;${tailscaleArgs}&lt;/span&gt;
			      
			      echo &amp;quot;Tailscale setup complete!&amp;quot;
			      tailscale status
			
			runcmd:
			  - /etc/tailscale-setup.sh
			
			final_message: &amp;quot;Tailscale setup completed. Check &amp;#x27;tailscale status&amp;#x27;.&amp;quot;
			`&lt;/span&gt;;
			  });
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;What&amp;#39;s happening here:&lt;/h4&gt;
&lt;p&gt;The &lt;code&gt;pulumi.output().apply()&lt;/code&gt; pattern is the pulumi way of handling values that might not be available until deployment time. Your auth key gets stored here as a secret, so we will need to unwrap it asyncronously at some point.&lt;/p&gt;
&lt;p&gt;Where generating a cloud-init.yml that:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Updates system packages (because security)&lt;/li&gt;
&lt;li&gt;Installs curl (need this for tailscale&amp;#39;s installer script)&lt;/li&gt;
&lt;li&gt;Writes a bash script to /etc/tailscale-setup.sh&lt;/li&gt;
&lt;li&gt;executes that script via r&lt;code&gt;uncmd&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The bash script does the heavy lifting:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Downloads and runs Tailscale&amp;#39;s official installer&lt;/li&gt;
&lt;li&gt;Enables and starts the talscaled systemd service&lt;/li&gt;
&lt;li&gt;Connects to the network using taislcale up with the auth key&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;set -euo pipefail&lt;/code&gt; means fail fast on errors&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;note: providing the --ssh flag tells Tailscale to handle SSH connections through its own protocol. This means Tailscale manages authentication and you get things like SSH session recording and access logs.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Creating Digital Ocean Resources&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; digitalocean &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@pulumi/digitalocean&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; pulumi &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@pulumi/pulumi&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { generateCloudInitUserData, &lt;span class=&quot;hljs-title class_&quot;&gt;TailscaleConfig&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../cloud-init&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;DigitalOceanVmConfig&lt;/span&gt; {
  &lt;span class=&quot;hljs-attr&quot;&gt;tailscale&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;TailscaleConfig&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;size&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;region&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;
  &lt;span class=&quot;hljs-attr&quot;&gt;monitoring&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;boolean&lt;/span&gt;;
}

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;createDigitalOceanDroplet&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;, 
  &lt;span class=&quot;hljs-attr&quot;&gt;config&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;DigitalOceanVmConfig&lt;/span&gt;
&lt;/span&gt;): digitalocean.&lt;span class=&quot;hljs-property&quot;&gt;Droplet&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; ubuntuImage = digitalocean.&lt;span class=&quot;hljs-title function_&quot;&gt;getImage&lt;/span&gt;({
    &lt;span class=&quot;hljs-attr&quot;&gt;slug&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;ubuntu-22-04-x64&amp;#x27;&lt;/span&gt;
  });

  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; userData = &lt;span class=&quot;hljs-title function_&quot;&gt;generateCloudInitUserData&lt;/span&gt;(config.&lt;span class=&quot;hljs-property&quot;&gt;tailscale&lt;/span&gt;);

  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; digitalocean.&lt;span class=&quot;hljs-title class_&quot;&gt;Droplet&lt;/span&gt;(name, {
    &lt;span class=&quot;hljs-attr&quot;&gt;image&lt;/span&gt;: ubuntuImage.&lt;span class=&quot;hljs-title function_&quot;&gt;then&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;img&lt;/span&gt; =&amp;gt;&lt;/span&gt; img.&lt;span class=&quot;hljs-property&quot;&gt;slug&lt;/span&gt; || img.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;toString&lt;/span&gt;()),
    &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: name,
    &lt;span class=&quot;hljs-attr&quot;&gt;region&lt;/span&gt;: config.&lt;span class=&quot;hljs-property&quot;&gt;region&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;sfo3&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;size&lt;/span&gt;: config.&lt;span class=&quot;hljs-property&quot;&gt;size&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;s-1vcpu-1gb&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;userData&lt;/span&gt;: userData,
    &lt;span class=&quot;hljs-attr&quot;&gt;tags&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;tailscale&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;pulumi-managed&amp;#x27;&lt;/span&gt;],
    &lt;span class=&quot;hljs-attr&quot;&gt;monitoring&lt;/span&gt;: config.&lt;span class=&quot;hljs-property&quot;&gt;monitoring&lt;/span&gt; || &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;ipv6&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
  });
}

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;createTailscaleFirewall&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;, 
  &lt;span class=&quot;hljs-attr&quot;&gt;dropletIds&lt;/span&gt;: pulumi.&lt;span class=&quot;hljs-title class_&quot;&gt;Input&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;number&lt;/span&gt;&amp;gt;[]
&lt;/span&gt;): digitalocean.&lt;span class=&quot;hljs-property&quot;&gt;Firewall&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; digitalocean.&lt;span class=&quot;hljs-title class_&quot;&gt;Firewall&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`&lt;span class=&quot;hljs-subst&quot;&gt;${name}&lt;/span&gt;-firewall`&lt;/span&gt;, {
    &lt;span class=&quot;hljs-attr&quot;&gt;name&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;`&lt;span class=&quot;hljs-subst&quot;&gt;${name}&lt;/span&gt;-tailscale-firewall`&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;dropletIds&lt;/span&gt;: dropletIds,
    
    &lt;span class=&quot;hljs-attr&quot;&gt;inboundRules&lt;/span&gt;: [
      {
        &lt;span class=&quot;hljs-attr&quot;&gt;protocol&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;udp&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;portRange&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;41641&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;sourceAddresses&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;0.0.0.0/0&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;::/0&amp;#x27;&lt;/span&gt;]
      },
      {
        &lt;span class=&quot;hljs-attr&quot;&gt;protocol&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;icmp&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;sourceAddresses&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;0.0.0.0/0&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;::/0&amp;#x27;&lt;/span&gt;]
      }
    ],
    
    &lt;span class=&quot;hljs-attr&quot;&gt;outboundRules&lt;/span&gt;: [
      {
        &lt;span class=&quot;hljs-attr&quot;&gt;protocol&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;tcp&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;portRange&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;all&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;destinationAddresses&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;0.0.0.0/0&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;::/0&amp;#x27;&lt;/span&gt;]
      },
      {
        &lt;span class=&quot;hljs-attr&quot;&gt;protocol&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;udp&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;portRange&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;all&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;destinationAddresses&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;0.0.0.0/0&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;::/0&amp;#x27;&lt;/span&gt;]
      },
      {
        &lt;span class=&quot;hljs-attr&quot;&gt;protocol&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;icmp&amp;#x27;&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;destinationAddresses&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;0.0.0.0/0&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;::/0&amp;#x27;&lt;/span&gt;]
      }
    ]
  });
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;What is going on here?&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;createDigitalOceanDroplet()&lt;/code&gt; assembles a droplet resources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Using an ubuntu 22.04 LTS image slug&lt;/li&gt;
&lt;li&gt;&lt;code&gt;userData&lt;/code&gt; is our cloud-init configuration passed to the VM on boot&lt;/li&gt;
&lt;li&gt;size is specifying the type of droplet&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ipv6: true&lt;/code&gt; because it&amp;#39;s 2025&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;createTailscaleFirewall()&lt;/code&gt; creates a DigitalOcean firewall with very specific rules:&lt;/p&gt;
&lt;p&gt;Inbound:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;UDP port 414641: Tailscale&amp;#39;s coordination port&lt;/li&gt;
&lt;li&gt;ICMP: For ping and network diagnostics&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Outbound:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Everything: The BM needs to reach package repos, Tailscale&amp;#39;s control plane, and other Tailscale nodes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Notice what is missing from the config...There is no SSH on port 22. The droplet will not be accessible via traditional SSH. You will not need to generate an SSH key for this. This is the security model we are after. &lt;/p&gt;
&lt;h2&gt;Deployment Orchestration&lt;/h2&gt;
&lt;p&gt;The main entry point &lt;code&gt;index.ts&lt;/code&gt; ties everything together&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; pulumi &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@pulumi/pulumi&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { 
  createDigitalOceanDroplet, 
  createTailscaleFirewall 
} &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./src/providers/digitalocean&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; config = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; pulumi.&lt;span class=&quot;hljs-title class_&quot;&gt;Config&lt;/span&gt;();
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tailscaleAuthKey = config.&lt;span class=&quot;hljs-title function_&quot;&gt;requireSecret&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;authkey&amp;#x27;&lt;/span&gt;);
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; instanceName = &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;tailscale-vm&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; droplet = &lt;span class=&quot;hljs-title function_&quot;&gt;createDigitalOceanDroplet&lt;/span&gt;(instanceName, {
  &lt;span class=&quot;hljs-attr&quot;&gt;tailscale&lt;/span&gt;: {
    &lt;span class=&quot;hljs-attr&quot;&gt;authKey&lt;/span&gt;: tailscaleAuthKey,
    &lt;span class=&quot;hljs-attr&quot;&gt;hostname&lt;/span&gt;: instanceName,
    &lt;span class=&quot;hljs-attr&quot;&gt;acceptRoutes&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;enableSSH&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;tags&lt;/span&gt;: [&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;tag:pulumi&amp;#x27;&lt;/span&gt;]
  },
  &lt;span class=&quot;hljs-attr&quot;&gt;size&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;s-1vcpu-1gb&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;region&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;sfo3&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;monitoring&lt;/span&gt;: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
});

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; firewall = &lt;span class=&quot;hljs-title function_&quot;&gt;createTailscaleFirewall&lt;/span&gt;(
  instanceName, 
  [droplet.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;apply&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;id&lt;/span&gt; =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;parseInt&lt;/span&gt;(id, &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt;))]
);

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; dropletId = droplet.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; publicIp = droplet.&lt;span class=&quot;hljs-property&quot;&gt;ipv4Address&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tailscaleHostname = instanceName;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; firewallId = firewall.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;The flow:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Load Pulumi config and grab the Tailscale auth key (stored as a secret)&lt;/li&gt;
&lt;li&gt;Create the droplet with Tailscale configuration&lt;/li&gt;
&lt;li&gt;Create the firewall and attach it to the droplet&lt;/li&gt;
&lt;li&gt;Export useful values (droplet ID, public IP, etc.)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The &lt;code&gt;droplet.id.apply(id =&amp;gt; parseInt(id, 10))&lt;/code&gt; is another Pulumi pattern. The droplet ID isn&amp;#39;t available until the resource is created, so we use &lt;code&gt;apply()&lt;/code&gt; to transform it asynchronously. DigitalOcean&amp;#39;s API returns IDs as strings, but the firewall resource expects integers. We parse it.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;acceptRoutes: true&lt;/code&gt; flag tells this node to accept routes advertised by other Tailscale nodes. Useful if you&amp;#39;re setting up subnet routing later.&lt;/p&gt;
&lt;h2&gt;Configure Tailscale Admin Panel&lt;/h2&gt;
&lt;h3&gt;Generate an Auth Key&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Navigate to the &lt;a href=&quot;https://login.tailscale.com/admin&quot;&gt;Tailscale Admin Console&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Settings&lt;/strong&gt; in the left sidebar  &lt;/li&gt;
&lt;li&gt;Select the &lt;strong&gt;Keys&lt;/strong&gt; tab  &lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Generate auth key&lt;/strong&gt;  &lt;/li&gt;
&lt;li&gt;Configure the auth key settings:  &lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description&lt;/strong&gt;: Enter &lt;code&gt;pulumi-deployment&lt;/code&gt; or similar  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reusable&lt;/strong&gt;: Leave &lt;strong&gt;unchecked&lt;/strong&gt; (each VM should use the key once)  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ephemeral&lt;/strong&gt;: Check this if you want VMs to disappear from Tailscale when destroyed  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Preauthorized&lt;/strong&gt;: &lt;strong&gt;Check this&lt;/strong&gt; (allows automatic approval without manual intervention)  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Expiration&lt;/strong&gt;: Set to your preference (90 days is common)  &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tags&lt;/strong&gt;: Optionally add tags like &lt;code&gt;tag:pulumi&lt;/code&gt; or &lt;code&gt;tag:server&lt;/code&gt; for ACL management&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Generate key&lt;/strong&gt;  &lt;/li&gt;
&lt;li&gt;**Copy the auth key - it looks like &lt;code&gt;tskey-auth-xxxxxxxxxxxxx-yyyyyyyyyyyyyyyy&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;Store this securely - you&amp;#39;ll need it in Step 3&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Optional: Configure ACLs for Tagged Nodes&lt;/h3&gt;
&lt;p&gt;It is my preference to setup ACL policy to include the tags from the auth key. It&amp;#39;s fairly easy to configure different groups and policies here.&lt;/p&gt;
&lt;p&gt;This would look something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;  
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;tagOwners&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;tag:pulumi&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;autogroup:admin&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;  
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;  
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;acls&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;    
	  &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;      
		  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;action&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;accept&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;      
		  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;src&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;autogroup:admin&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;      
		  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;dst&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tag:pulumi:*&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;    
	  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;  
  &lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;  &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Don&amp;#39;t forget to click save to apply the ACL changes.&lt;/p&gt;
&lt;h2&gt;Configure Cloud Provider&lt;/h2&gt;
&lt;p&gt;Digital Ocean is how I tested this, but it is simple enough to add this sort of thing to aws. First you need to get an API token from &lt;a href=&quot;https://cloud.digitalocean.com/account/api/tokens&quot;&gt;cloud.digitalocean.com/account/api/tokens&lt;/a&gt;. The instructions generally are along these lines:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Generate a New Token&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Fill in the required form fields:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Token Name: Give it a descriptive name (e.g. &amp;quot;pulum-droplet-setup&amp;quot;)&lt;/li&gt;
&lt;li&gt;Expiration: Choose an appropriate expiration time&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set Scopes:&lt;/p&gt;
&lt;p&gt; For setting up droplets with firewall permissions, you should select something like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;droplet:create&lt;/strong&gt; + &lt;strong&gt;droplet:read&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;firewall:create&lt;/strong&gt; + &lt;strong&gt;firewall:read&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;firewall:update&lt;/strong&gt; + &lt;strong&gt;firewall:read&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;project:read&lt;/strong&gt; (often required)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Store this key securely for the next steps&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;Note: it took me a bit to figure out the scopes and they may change based on how you set up this repo. Don&amp;#39;t be shy to experiment with what you want to add to your droplet our automate in pulumi.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Initialize Pulumi Stack&lt;/h2&gt;
&lt;p&gt;Now we set the following variables in your pulumi config. One of the handy things is that using the --secret flag will encrypt any secrets added to this so it&amp;#39;s fairly safe to have them committed to the code base.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Initialize a new stack&lt;/span&gt;
pulumi stack init dev

&lt;span class=&quot;hljs-comment&quot;&gt;# Set provider to DigitalOcean (build this so aws, etc can be added)  &lt;/span&gt;
pulumi config &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; tailscale-pulumi:provider digitalocean  

&lt;span class=&quot;hljs-comment&quot;&gt;# Set your Tailscale auth key&lt;/span&gt;
pulumi config &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; tailscale-pulumi:authkey tskey-auth-xxxxx --secret

&lt;span class=&quot;hljs-comment&quot;&gt;# Set your DigitalOcean API token&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# Generate one at: https://cloud.digitalocean.com/account/api/tokens&lt;/span&gt;
pulumi config &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; digitalocean:token dop_v1_xxxxx --secret&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Preview Infrastructure&lt;/h2&gt;
&lt;p&gt;Before deploying, preview what Pulumi will create:  &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npm run preview&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pulumi will show you a plan of what it will create. Review it. Make sure nothing looks weird.&lt;/p&gt;
&lt;h2&gt;Deploy Infrastructure&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npm run deploy&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pulumi will:  &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create the VM with cloud-init configuration  &lt;/li&gt;
&lt;li&gt;Set up firewall rules (only Tailscale UDP port 41641 and ICMP allowed)  &lt;/li&gt;
&lt;li&gt;On first boot, the VM will automatically:  &lt;ul&gt;
&lt;li&gt;Install Tailscale  &lt;/li&gt;
&lt;li&gt;Authenticate with your auth key  &lt;/li&gt;
&lt;li&gt;Join your Tailscale network  &lt;/li&gt;
&lt;li&gt;Configure SSH access through Tailscale&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The deployment takes 2-3 minutes. Watch for the outputs at the end something like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;Outputs:  
    dropletId         : &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;123456789&amp;quot;&lt;/span&gt;    
    publicIp          : &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;192.0.2.100&amp;quot;&lt;/span&gt;    
    tailscaleHostname : &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tailscale-vm&amp;quot;&lt;/span&gt;
    firewallId        : &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;abv123&amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Step 7: Verify Tailscale Connection&lt;/h2&gt;
&lt;h3&gt;Check Tailscale Admin Console&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Go to the &lt;a href=&quot;https://login.tailscale.com/admin/machines&quot;&gt;Tailscale Machines page&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;Look for your new machine with hostname &lt;code&gt;tailscale-vm&lt;/code&gt;  &lt;/li&gt;
&lt;li&gt;It should show as &lt;strong&gt;Connected&lt;/strong&gt; with a green indicator  &lt;/li&gt;
&lt;li&gt;Note the Tailscale IP address (usually &lt;code&gt;100.x.x.x&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;SSH into Your VM via Tailscale&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Use the Tailscale hostname or IP  &lt;/span&gt;
ssh root@tailscale-vm  
  
&lt;span class=&quot;hljs-comment&quot;&gt;# Or use the Tailscale IP directly  &lt;/span&gt;
ssh root@100.x.x.x  &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Traditional SSH on port 22 is NOT exposed to the internet. Access is exclusively through the Tailscale network.  &lt;/p&gt;
&lt;h3&gt;Verify Tailscale Status on the VM&lt;/h3&gt;
&lt;p&gt;Once connected via SSH:  &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Check Tailscale status  &lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; tailscale status  
  
&lt;span class=&quot;hljs-comment&quot;&gt;# View full network status  &lt;/span&gt;
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; tailscale status --json  
  
&lt;span class=&quot;hljs-comment&quot;&gt;# Test connectivity to other Tailscale nodes  &lt;/span&gt;
tailscale ping &amp;lt;another-tailscale-device&amp;gt;  &lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Congratulations You Now Have a Child...Server&lt;/h2&gt;
&lt;p&gt;What have you created? A reproducible IaC setup that deploys VMs with zero-trust networking baked in. The Infrastrcutre Aas Code can be versioned in Git. You can deploy a hoard of these onto the internet and they will be identical twins. You can also delete things in bulk if needed. &lt;/p&gt;
&lt;p&gt;The security model is worth appreciating. We have no SSH keys to manage, which was the main driver for this. The scenario I kept encountering was working on projects and having people come and go, and trying to remember who had server access and who didn&amp;#39;t this is much easier to manage via an identify provider and Tailscale authentication. Access can then be managed centrally through a Tailscale ACL.&lt;/p&gt;
&lt;h3&gt;Extending this&lt;/h3&gt;
&lt;p&gt;Some ideas for experimentation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Buld a different provider like aws and deploy there&lt;/li&gt;
&lt;li&gt;Add multiple droplets in different regions&lt;/li&gt;
&lt;li&gt;Configure subnet routing to access private networks&lt;/li&gt;
&lt;li&gt;Set up Tailscale&amp;#39;s MagicDNS for internal service discovery&lt;/li&gt;
&lt;li&gt;Implement tagging strategies for fine-grained ACL control&lt;/li&gt;
&lt;li&gt;Automate certificate management with Tailscale&amp;#39;s built-in HTTPS support&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The pattern scales. You can adapt this to AWS, GCP, Azure, or any provider with cloud-init support. The cloud-init script remains largely unchanged.&lt;/p&gt;
</content>
</entry>
<entry>
<title>Setting Up Dockerized PostgreSQL with Multi-Tenant Support and Automated Migrations</title>
<link href="https://spriggansecurity.com/blog/building-multi-tenant-apps-with-mikroorm/"/>
<id>https://spriggansecurity.com/blog/building-multi-tenant-apps-with-mikroorm/</id>
<published>2025-04-21T00:00:00.000Z</published>
<updated>2025-04-21T00:00:00.000Z</updated>
<category term="database"/><category term="db"/><category term="postgres"/><category term="mikro-orm"/><category term="docker"/><category term="typescript"/>
<summary>Imagine creating a single application that serves dozens, hundreds, or even thousands of different clients, each with their own private data that remains completely…</summary>
<content type="html">&lt;p&gt;Imagine creating a single application that serves dozens, hundreds, or even thousands of different clients, each with their own private data that remains completely isolated from others. That&amp;#39;s the magic of multi-tenancy - a powerful architectural pattern that&amp;#39;s the backbone of most modern SaaS platforms.&lt;/p&gt;
&lt;p&gt;In this hands-on guide, I&amp;#39;ll walk you through creating a robust multi-tenant application using Node.js, Express, MikroORM, and PostgreSQL. We&amp;#39;ll build a farm management system where each farm organization (tenant) gets its own isolated database, ensuring complete data separation while sharing a single codebase. Will it be perfect, probably not. Will it do the thing with some basic adherence to best practices. I sure hope so!?&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Multi-tenancy is like running a shared office building.&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;Tenants each get their own:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Private keycard access&lt;/strong&gt; (authentication)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Locked offices &amp;amp; meeting rooms&lt;/strong&gt; (data isolation)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Guaranteed desk space&lt;/strong&gt; (resource quotas)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;…but they all share:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The same HVAC, elevators, and internet&lt;/strong&gt; (infrastructure)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A single maintenance crew&lt;/strong&gt; (your ops team)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One security system&lt;/strong&gt; (global monitoring)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No one’s building a whole new skyscraper just because another company moves in.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; One building, many tenants—no construction required.&lt;/p&gt;
&lt;h2&gt;Real-World Multi-Tenant Applications&lt;/h2&gt;
&lt;p&gt;Before diving in, let&amp;#39;s consider some real-world applications of multi-tenancy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Expense Tracking Apps&lt;/strong&gt;: Services like &lt;strong&gt;&lt;a href=&quot;https://www.waveapps.com&quot;&gt;Wave Accounting&lt;/a&gt;&lt;/strong&gt; serve hundreds of businesses, each company seeing only their own expense reports and data&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Customer Relationship Management (CRM)&lt;/strong&gt;: Platforms like &lt;strong&gt;&lt;a href=&quot;https://www.hubspot.com/products/crm&quot;&gt;HubSpot CRM&lt;/a&gt;&lt;/strong&gt; allow each business to manage their customers without seeing data from other companies&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Content Management Systems (CMS)&lt;/strong&gt;: Services like &lt;strong&gt;&lt;a href=&quot;https://carrd.co/&quot;&gt;Carrd&lt;/a&gt;&lt;/strong&gt; host thousands of sites where each owner manages only their content&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;E-commerce Platforms&lt;/strong&gt;: &lt;strong&gt;&lt;a href=&quot;https://www.bigcartel.com&quot;&gt;Big Cartel&lt;/a&gt;&lt;/strong&gt; hosts many independent stores on the same infrastructure&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For this example I&amp;#39;m going to use a simple farm management system. I was building an app to help my friend manage their Community Supported Agriculture business. This seemed like a good opportunity to build a SaaS product that other farmers could use. This would require a sort of white labeling effort, and converting the system to handle multi tenancy.&lt;/p&gt;
&lt;p&gt;I simplified all of this to demo the functionality. Our farm management system will follow the same principles - allowing different farm organizations to manage their crops, harvests, and users without seeing each other&amp;#39;s data.&lt;/p&gt;
&lt;h2&gt;What You&amp;#39;ll Learn&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Creating a multi-tenant architecture with database-per-tenant isolation&lt;/li&gt;
&lt;li&gt;Implementing dynamic tenant routing in Express&lt;/li&gt;
&lt;li&gt;Managing tenant-specific database connections with MikroORM&lt;/li&gt;
&lt;li&gt;Handling tenant-specific migrations&lt;/li&gt;
&lt;li&gt;Establishing database schema with agricultural-themed entities&lt;/li&gt;
&lt;li&gt;Testing your multi-tenant setup to ensure all tenant databases work correctly&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Project Setup&lt;/h2&gt;
&lt;p&gt;Let&amp;#39;s start by setting up the project:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; farm-management &amp;amp;&amp;amp; &lt;span class=&quot;hljs-built_in&quot;&gt;cd&lt;/span&gt; farm-management
npm init -y
npm install @mikro-orm/core @mikro-orm/postgresql @mikro-orm/migrations @mikro-orm/cli pg express dotenv uuid
npm install -D typescript @types/node @types/express @types/uuid ts-node nodemon
npx tsc --init&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Update &lt;code&gt;tsconfig.json&lt;/code&gt; with appropriate settings for TypeScript. If you want to explore more working configs for different runtime environments. I&amp;#39;ve found this repo &lt;a href=&quot;https://github.com/tsconfig/bases&quot;&gt;tsconfig / bases&lt;/a&gt; to be extremely helpful:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;compilerOptions&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;target&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;es2022&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;module&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;es2022&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;moduleResolution&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Node&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;rootDir&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./src&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;outDir&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./dist&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;strict&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;esModuleInterop&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;experimentalDecorators&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;emitDecoratorMetadata&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;skipLibCheck&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;forceConsistentCasingInFileNames&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;resolveJsonModule&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;true&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;types&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;node&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;baseUrl&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;.&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;paths&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@/*&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;src/*&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;include&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;src/**/*&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;exclude&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;hljs-punctuation&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;node_modules&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;dist&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tests&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&amp;#39;s create a logical directory structure that will help us organize our multi-tenant application:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;src/
  entities/     # Our database models that define the application's data structure
  migrations/   # Database migration files for evolving our schema
  config/       # Configuration files for environment variables and ORM settings
  services/     # Business logic services, including our TenantManager
  middleware/   # Express middleware, especially for tenant context handling
  routes/       # API routes for both tenant-specific and global endpoints&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This structure keeps our concerns nicely separated and makes it easier to navigate the codebase as it grows. There are a lot of different approaches to organizing a project, feel free to structure this in a way that works for your flow.&lt;/p&gt;
&lt;h2&gt;Database Entity Models&lt;/h2&gt;
&lt;p&gt;For our farm management system, we&amp;#39;ll create the following entities:&lt;/p&gt;
&lt;h3&gt;Base Entity&lt;/h3&gt;
&lt;p&gt;First, let&amp;#39;s define a base entity that all other entities will extend:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/BaseEntity.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;PrimaryKey&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Property&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;@mikro-orm/core&amp;quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;abstract&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;BaseEntity&lt;/span&gt; {
  &lt;span class=&quot;hljs-meta&quot;&gt;@PrimaryKey&lt;/span&gt;()
  id!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  &lt;span class=&quot;hljs-attr&quot;&gt;createdAt&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt;();

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;onUpdate&lt;/span&gt;: &lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt;() })
  &lt;span class=&quot;hljs-attr&quot;&gt;updatedAt&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt;();
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Organization Entity (Tenant)&lt;/h3&gt;
&lt;p&gt;The Organization entity represents a farm tenant, this usually contains stuff like branding, and any site context specific stuff that the organization would need:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/Organization.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Entity&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Property&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Unique&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;@mikro-orm/core&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;BaseEntity&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./BaseEntity&amp;quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-meta&quot;&gt;@Entity&lt;/span&gt;()
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;BaseEntity&lt;/span&gt; {
  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  &lt;span class=&quot;hljs-meta&quot;&gt;@Unique&lt;/span&gt;()
  name!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  &lt;span class=&quot;hljs-attr&quot;&gt;logoUrl&lt;/span&gt;?: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  farmType!: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;vegetable&amp;#x27;&lt;/span&gt; | &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;dairy&amp;#x27;&lt;/span&gt; | &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;orchard&amp;#x27;&lt;/span&gt; | &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;mixed&amp;#x27;&lt;/span&gt;;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;User Entity&lt;/h3&gt;
&lt;p&gt;Each farm has users that can access the system:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/User.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Entity&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Property&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;ManyToOne&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Unique&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;@mikro-orm/core&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./Organization&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;BaseEntity&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./BaseEntity&amp;quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-meta&quot;&gt;@Entity&lt;/span&gt;()
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;User&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;BaseEntity&lt;/span&gt; {
  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  firstName!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  lastName!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  &lt;span class=&quot;hljs-meta&quot;&gt;@Unique&lt;/span&gt;()
  email!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@ManyToOne&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;)
  organization!: &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Farm-Specific Entities&lt;/h3&gt;
&lt;p&gt;Now let&amp;#39;s create entities specific to farm operations:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/Crop.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Entity&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Property&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;ManyToOne&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;@mikro-orm/core&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./Organization&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;BaseEntity&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./BaseEntity&amp;quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-meta&quot;&gt;@Entity&lt;/span&gt;()
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;BaseEntity&lt;/span&gt; {
  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  name!: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  plantingDate!: &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@ManyToOne&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;)
  organization!: &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;;
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/Harvest.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Entity&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Property&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;ManyToOne&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;@mikro-orm/core&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./Crop&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./Organization&amp;quot;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;BaseEntity&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;./BaseEntity&amp;quot;&lt;/span&gt;;

&lt;span class=&quot;hljs-meta&quot;&gt;@Entity&lt;/span&gt;()
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Harvest&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;BaseEntity&lt;/span&gt; {
  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  quantity!: &lt;span class=&quot;hljs-built_in&quot;&gt;number&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@Property&lt;/span&gt;()
  unit!: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;kg&amp;#x27;&lt;/span&gt; | &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;bushel&amp;#x27;&lt;/span&gt; | &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;crate&amp;#x27;&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@ManyToOne&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;)
  crop!: &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;;

  &lt;span class=&quot;hljs-meta&quot;&gt;@ManyToOne&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;)
  organization!: &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Entity Index&lt;/h3&gt;
&lt;p&gt;Create an index file to export all entities. I usually use &lt;a href=&quot;https://www.npmjs.com/package/barrelsby&quot;&gt;barrelsby&lt;/a&gt; as a way to manage generating indexes quickly. Overall the goal is to make imports less messy:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/entities/index.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./BaseEntity.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./Organization.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./User.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./Crop.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; * &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./Harvest.js&amp;#x27;&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;MikroORM Configuration&lt;/h2&gt;
&lt;p&gt;Now we&amp;#39;ll set up MikroORM to handle both the base database and tenant-specific databases:&lt;/p&gt;
&lt;h3&gt;Environment Configuration&lt;/h3&gt;
&lt;p&gt;First, create an environment configuration file, this step is optional. You can always just directly reference the env variables you need in a file by using &lt;code&gt;process.env.VARIABLE&lt;/code&gt; in a definition, which works nicely:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/config/env.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; dotenv &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;dotenv&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; path &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;path&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { fileURLToPath } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;url&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; __filename = &lt;span class=&quot;hljs-title function_&quot;&gt;fileURLToPath&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;meta&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;url&lt;/span&gt;);
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; __dirname = path.&lt;span class=&quot;hljs-title function_&quot;&gt;dirname&lt;/span&gt;(__filename);

&lt;span class=&quot;hljs-comment&quot;&gt;// Load environment variables from .env file&lt;/span&gt;
dotenv.&lt;span class=&quot;hljs-title function_&quot;&gt;config&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;path&lt;/span&gt;: path.&lt;span class=&quot;hljs-title function_&quot;&gt;resolve&lt;/span&gt;(__dirname, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../../.env&amp;#x27;&lt;/span&gt;) });

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; env = {
  &lt;span class=&quot;hljs-attr&quot;&gt;NODE_ENV&lt;/span&gt;: process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;NODE_ENV&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;development&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;DB_HOST&lt;/span&gt;: process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;DB_HOST&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;localhost&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;DB_PORT&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;Number&lt;/span&gt;(process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;DB_PORT&lt;/span&gt;) || &lt;span class=&quot;hljs-number&quot;&gt;5432&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;DB_NAME&lt;/span&gt;: process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;DB_NAME&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;farm_tenants&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;DB_USER&lt;/span&gt;: process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;DB_USER&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;farmadmin&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;DB_PASSWORD&lt;/span&gt;: process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;DB_PASSWORD&lt;/span&gt; || &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;harvest2025&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;PORT&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;Number&lt;/span&gt;(process.&lt;span class=&quot;hljs-property&quot;&gt;env&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;PORT&lt;/span&gt;) || &lt;span class=&quot;hljs-number&quot;&gt;3000&lt;/span&gt;,
};&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Base MikroORM Configuration&lt;/h3&gt;
&lt;p&gt;Now, define the base MikroORM configuration. If you have a long list of entities, this is where, something like barrelsy and having index files can come in handy. Especially for long lists of entities. This could change the import to something like &lt;code&gt;import * as Entities from &amp;#39;../entities/index.js&lt;/code&gt;. Then in the entities assignment in the config we could have &lt;code&gt;entities: Object.values(Entities)&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/config/mikro-orm.config.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Options&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/core&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;PostgreSqlDriver&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/postgresql&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { env } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./env.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;User&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Harvest&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../entities/index.js&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;options&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;Options&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-title class_&quot;&gt;PostgreSqlDriver&lt;/span&gt;&amp;gt; = {
  &lt;span class=&quot;hljs-attr&quot;&gt;entities&lt;/span&gt;: [&lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;User&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;Harvest&lt;/span&gt;],
  &lt;span class=&quot;hljs-attr&quot;&gt;dbName&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;DB_NAME&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;host&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;DB_HOST&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;port&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;DB_PORT&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;user&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;DB_USER&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;password&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;DB_PASSWORD&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;driver&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;PostgreSqlDriver&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;debug&lt;/span&gt;: env.&lt;span class=&quot;hljs-property&quot;&gt;NODE_ENV&lt;/span&gt; === &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;development&amp;#x27;&lt;/span&gt;,
  &lt;span class=&quot;hljs-attr&quot;&gt;migrations&lt;/span&gt;: {
    &lt;span class=&quot;hljs-attr&quot;&gt;tableName&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;mikro_orm_migrations&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;path&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./dist/migrations&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-attr&quot;&gt;pathTs&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./src/migrations&amp;#x27;&lt;/span&gt;,
  },
};

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;default&lt;/span&gt; options;&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Tenant Management&lt;/h2&gt;
&lt;p&gt;The heart of our multi-tenant system is the &lt;code&gt;TenantManager&lt;/code&gt; class, which dynamically creates and manages connections to tenant databases. This is perhaps the most crucial piece of our multi-tenant architecture:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/services/TenantManager.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;RequestContext&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/core&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;PostgreSqlDriver&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/postgresql&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; baseOptions &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../config/mikro-orm.config.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; fs &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;fs&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; path &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;path&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { fileURLToPath } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;url&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; __filename = &lt;span class=&quot;hljs-title function_&quot;&gt;fileURLToPath&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;meta&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;url&lt;/span&gt;);
&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; __dirname = path.&lt;span class=&quot;hljs-title function_&quot;&gt;dirname&lt;/span&gt;(__filename);

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;private&lt;/span&gt; tenantOrmInstances = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Map&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;, &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;&amp;gt;();
  &lt;span class=&quot;hljs-keyword&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;baseOrm&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt; | &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt; = &lt;span class=&quot;hljs-literal&quot;&gt;null&lt;/span&gt;;

  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;getBaseORM&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (!&lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;baseOrm&lt;/span&gt;) {
      &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;baseOrm&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;init&lt;/span&gt;(baseOptions);
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;baseOrm&lt;/span&gt;;
  }

  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;getTenantORM&lt;/span&gt;(&lt;span class=&quot;hljs-attr&quot;&gt;tenantId&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (!&lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;tenantOrmInstances&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;has&lt;/span&gt;(tenantId)) {
      &lt;span class=&quot;hljs-comment&quot;&gt;// Create a new database for this tenant if it doesn&amp;#x27;t exist&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; baseOrm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getBaseORM&lt;/span&gt;();
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; connection = baseOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getConnection&lt;/span&gt;();
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
        &lt;span class=&quot;hljs-comment&quot;&gt;// Check if the tenant database exists&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; result = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(
          &lt;span class=&quot;hljs-string&quot;&gt;`SELECT 1 FROM pg_database WHERE datname = $1`&lt;/span&gt;,
          [&lt;span class=&quot;hljs-string&quot;&gt;`tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;]
        );

        &lt;span class=&quot;hljs-comment&quot;&gt;// If the database doesn&amp;#x27;t exist, create it&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (result.&lt;span class=&quot;hljs-property&quot;&gt;length&lt;/span&gt; === &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;) {
          &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`CREATE DATABASE tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Created new database for tenant: tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
        }
      } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Error checking/creating tenant database: &lt;span class=&quot;hljs-subst&quot;&gt;${error.message}&lt;/span&gt;`&lt;/span&gt;);
      }

      &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize tenant ORM&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantOptions = {
        ...baseOptions,
        &lt;span class=&quot;hljs-attr&quot;&gt;dbName&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;`tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;,
        &lt;span class=&quot;hljs-attr&quot;&gt;migrations&lt;/span&gt;: {
          &lt;span class=&quot;hljs-attr&quot;&gt;tableName&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;mikro_orm_migrations_tenant&amp;#x27;&lt;/span&gt;,
          &lt;span class=&quot;hljs-attr&quot;&gt;path&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./dist/migrations/tenant&amp;#x27;&lt;/span&gt;,
          &lt;span class=&quot;hljs-attr&quot;&gt;pathTs&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./src/migrations/tenant&amp;#x27;&lt;/span&gt;,
        }
      };

      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; orm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;init&lt;/span&gt;(tenantOptions);
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Run migrations to ensure the schema is up to date&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; migrator = orm.&lt;span class=&quot;hljs-title function_&quot;&gt;getMigrator&lt;/span&gt;();
        &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; migrator.&lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;();
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Migrations applied for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
      } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Migrations not applied for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;: &lt;span class=&quot;hljs-subst&quot;&gt;${error.message}&lt;/span&gt;`&lt;/span&gt;);
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Creating schema manually for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;...`&lt;/span&gt;);
        
        &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize the schema manually for tenant&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Creating tenant schema manually...&amp;#x27;&lt;/span&gt;);
          &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; schemaPath = path.&lt;span class=&quot;hljs-title function_&quot;&gt;resolve&lt;/span&gt;(__dirname, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;..&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;..&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;src&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;schema.sql&amp;#x27;&lt;/span&gt;);
          &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; schema = fs.&lt;span class=&quot;hljs-title function_&quot;&gt;readFileSync&lt;/span&gt;(schemaPath, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;utf8&amp;#x27;&lt;/span&gt;);
          
          &lt;span class=&quot;hljs-comment&quot;&gt;// Split into individual statements and execute them&lt;/span&gt;
          &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; statements = schema.&lt;span class=&quot;hljs-title function_&quot;&gt;split&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;;&amp;#x27;&lt;/span&gt;)
            .&lt;span class=&quot;hljs-title function_&quot;&gt;map&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;s&lt;/span&gt; =&amp;gt;&lt;/span&gt; s.&lt;span class=&quot;hljs-title function_&quot;&gt;trim&lt;/span&gt;())
            .&lt;span class=&quot;hljs-title function_&quot;&gt;filter&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;s&lt;/span&gt; =&amp;gt;&lt;/span&gt; s.&lt;span class=&quot;hljs-property&quot;&gt;length&lt;/span&gt; &amp;gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;);
          
          &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantConnection = orm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getConnection&lt;/span&gt;();
          
          &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; (&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; statement &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt; statements) {
            &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
              &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantConnection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(statement);
            } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;err&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
              &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;warn&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Warning executing statement for tenant: &lt;span class=&quot;hljs-subst&quot;&gt;${err.message}&lt;/span&gt;`&lt;/span&gt;);
            }
          }
          
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Schema created successfully for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
        } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;schemaError&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Error creating schema for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;:`&lt;/span&gt;, schemaError.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt;);
        }
      }

      &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;tenantOrmInstances&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;set&lt;/span&gt;(tenantId, orm);
    }
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;tenantOrmInstances&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;get&lt;/span&gt;(tenantId)!;
  }

  &lt;span class=&quot;hljs-comment&quot;&gt;// Utility method to run operations in the context of a tenant&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; runInTenantContext&amp;lt;T&amp;gt;(&lt;span class=&quot;hljs-attr&quot;&gt;tenantId&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;, &lt;span class=&quot;hljs-attr&quot;&gt;callback&lt;/span&gt;: &lt;span class=&quot;hljs-function&quot;&gt;(&lt;span class=&quot;hljs-params&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;em&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;&lt;/span&gt;) =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;T&amp;gt;): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;T&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; orm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getTenantORM&lt;/span&gt;(tenantId);
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; em = orm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;fork&lt;/span&gt;();
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;RequestContext&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;create&lt;/span&gt;(em, &lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;callback&lt;/span&gt;(em));
  }

  &lt;span class=&quot;hljs-comment&quot;&gt;// Clean up resources when shutting down&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;closeConnections&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;void&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (&lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;baseOrm&lt;/span&gt;) {
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;baseOrm&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;close&lt;/span&gt;();
    }
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; (&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; [_, orm] &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-property&quot;&gt;tenantOrmInstances&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;entries&lt;/span&gt;()) {
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; orm.&lt;span class=&quot;hljs-title function_&quot;&gt;close&lt;/span&gt;();
    }
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;How the TenantManager Works&lt;/h3&gt;
&lt;p&gt;Let&amp;#39;s break down what makes this &lt;code&gt;TenantManager&lt;/code&gt; so powerful:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Connection Pool Management&lt;/strong&gt;: The &lt;code&gt;TenantManager&lt;/code&gt; maintains a map of MikroORM instances, one for each tenant. This prevents us from creating unnecessary database connections and ensures we reuse existing connections when possible.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Lazy Initialization&lt;/strong&gt;: Tenant databases are only created and connected when they&amp;#39;re first requested, not upfront. This means our application can scale to thousands of tenants without wasting resources on idle connections.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Automatic Database Creation&lt;/strong&gt;: When a tenant is requested for the first time, the manager checks if their database exists and creates it if needed. This simplifies tenant onboarding tremendously.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Migration Handling&lt;/strong&gt;: Each tenant database gets automatically migrated to the latest schema version on first access. This ensures database consistency across all tenants.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fallback Mechanism&lt;/strong&gt;: If migrations fail (perhaps because the database is brand new), the manager can initialize the schema manually from SQL statements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource Cleanup&lt;/strong&gt;: When the application shuts down, all database connections are properly closed to prevent resource leaks.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The &lt;code&gt;runInTenantContext&lt;/code&gt; method is particularly useful when you need to perform operations for a specific tenant outside of the standard request flow. It ensures that database operations are executed within the correct tenant&amp;#39;s context.&lt;/p&gt;
&lt;h4&gt;Some Things We Don&amp;#39;t Address:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;proper caching using something like &lt;a href=&quot;https://www.geeksforgeeks.org/lru-cache-implementation/&quot;&gt;LRU caching&lt;/a&gt;Which will ensure that the cache doesn&amp;#39;t get stale and cannot grow indefinitely. &lt;/li&gt;
&lt;li&gt;connection pooling issues that may arise when have many tenants trying to connect to a postgres database.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a href=&quot;https://mikro-orm.io/docs/usage-with-sql&quot;&gt;Check out MikroORM&amp;#39;s documentation&lt;/a&gt; for more details on working with PostgreSQL and managing database connections.&lt;/p&gt;
&lt;h2&gt;Express Middleware for Tenant Context&lt;/h2&gt;
&lt;p&gt;For a multi-tenant system to work properly, each incoming request needs to be associated with the correct tenant. Our Express middleware accomplishes this by extracting the tenant ID from either a custom HTTP header or from the subdomain, then setting up the appropriate database context for the request:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/middleware/tenantMiddleware.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;RequestHandler&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;express&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../services/TenantManager.js&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantMiddleware = (&lt;span class=&quot;hljs-attr&quot;&gt;tenantManager&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt;): &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;RequestHandler&lt;/span&gt; =&amp;gt;&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; (req, res, next) =&amp;gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// Extract tenant ID from custom header or from the subdomain&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantId = req.&lt;span class=&quot;hljs-property&quot;&gt;headers&lt;/span&gt;[&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;x-tenant-id&amp;#x27;&lt;/span&gt;] || req.&lt;span class=&quot;hljs-property&quot;&gt;hostname&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;split&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;.&amp;#x27;&lt;/span&gt;)[&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;];
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (!tenantId) {
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;400&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Tenant identification required&amp;#x27;&lt;/span&gt; });
    }

    &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
      &lt;span class=&quot;hljs-comment&quot;&gt;// Get the ORM instance for this tenant&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantORM = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getTenantORM&lt;/span&gt;(tenantId &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;string&lt;/span&gt;);
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Attach the tenant&amp;#x27;s ORM to the request object for use in route handlers&lt;/span&gt;
      (req &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;).&lt;span class=&quot;hljs-property&quot;&gt;tenantORM&lt;/span&gt; = tenantORM;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Continue to the next middleware or route handler&lt;/span&gt;
      &lt;span class=&quot;hljs-title function_&quot;&gt;next&lt;/span&gt;();
    } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (error) {
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;500&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Error initializing tenant context&amp;#x27;&lt;/span&gt; });
    }
  };
};&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;How Tenant Context Works&lt;/h3&gt;
&lt;p&gt;This middleware accomplishes several important tasks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Tenant Identification&lt;/strong&gt;: It determines which tenant is making the request by looking for the &lt;code&gt;x-tenant-id&lt;/code&gt; header or extracting it from the subdomain (e.g., &lt;code&gt;tenant-name.example.com&lt;/code&gt;).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Request Enrichment&lt;/strong&gt;: It attaches the tenant&amp;#39;s MikroORM instance to the request object, making it available to all downstream route handlers.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Lazy Initialization&lt;/strong&gt;: If this is the first request from a tenant, the middleware triggers the database creation and migration process via the &lt;code&gt;TenantManager&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;: If something goes wrong while setting up the tenant context, it returns an appropriate error response.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This approach has several advantages in a multi-tenant system:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Clean Route Handlers&lt;/strong&gt;: Your route handlers don&amp;#39;t need to worry about tenant identification or database selection - they just use &lt;code&gt;req.tenantORM&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Flexible Tenant Identification&lt;/strong&gt;: You can easily change how tenants are identified (headers, subdomains, path parameters) by modifying just this middleware.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Request Isolation&lt;/strong&gt;: Each request is processed in isolation with its own tenant context, preventing data leakage between tenants.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our application, we apply this middleware selectively to routes that need tenant context, while leaving other routes (like tenant management endpoints) available without tenant context:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// Apply tenant middleware only to tenant-specific API routes&lt;/span&gt;
app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/api&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;tenantMiddleware&lt;/span&gt;(tenantManager));
app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/api/crops&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;createCropRoutes&lt;/span&gt;());

&lt;span class=&quot;hljs-comment&quot;&gt;// Routes NOT requiring tenant context&lt;/span&gt;
app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/organizations&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;createOrganizationRoutes&lt;/span&gt;(tenantManager));&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This way, a request to &lt;code&gt;/api/crops&lt;/code&gt; would require tenant identification and would operate on the tenant&amp;#39;s database, while a request to &lt;code&gt;/organizations&lt;/code&gt; would operate on the global database without tenant context.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://expressjs.com/en/guide/using-middleware.html&quot;&gt;Learn more about middleware in Express.js&lt;/a&gt; to understand how middleware chains work.&lt;/p&gt;
&lt;h2&gt;API Routes&lt;/h2&gt;
&lt;p&gt;Now let&amp;#39;s create routes for our application:&lt;/p&gt;
&lt;h3&gt;Organization Routes (non-tenant specific)&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/routes/organizationRoutes.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Router&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;express&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../services/TenantManager.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../entities/index.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { v4 &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; uuidv4 } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;uuid&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;createOrganizationRoutes&lt;/span&gt; = (&lt;span class=&quot;hljs-params&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;tenantManager&lt;/span&gt;: &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt;&lt;/span&gt;) =&amp;gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; router = &lt;span class=&quot;hljs-title class_&quot;&gt;Router&lt;/span&gt;();

  &lt;span class=&quot;hljs-comment&quot;&gt;// Get all organizations&lt;/span&gt;
  router.&lt;span class=&quot;hljs-title function_&quot;&gt;get&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; (req, res) =&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; baseOrm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getBaseORM&lt;/span&gt;();
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; organizations = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; baseOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;find&lt;/span&gt;(&lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;, {});
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;(organizations);
    } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;500&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt; });
    }
  });

  &lt;span class=&quot;hljs-comment&quot;&gt;// Create a new organization (and tenant database)&lt;/span&gt;
  router.&lt;span class=&quot;hljs-title function_&quot;&gt;post&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; (req, res) =&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; { name, logoUrl, farmType } = req.&lt;span class=&quot;hljs-property&quot;&gt;body&lt;/span&gt;;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Validate required fields&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (!name || !farmType) {
        &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;400&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Name and farm type are required&amp;#x27;&lt;/span&gt; });
      }
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Create the organization in the base database&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; baseOrm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getBaseORM&lt;/span&gt;();
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; organization = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Organization&lt;/span&gt;();
      organization.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt; = &lt;span class=&quot;hljs-title function_&quot;&gt;uuidv4&lt;/span&gt;();
      organization.&lt;span class=&quot;hljs-property&quot;&gt;name&lt;/span&gt; = name;
      organization.&lt;span class=&quot;hljs-property&quot;&gt;logoUrl&lt;/span&gt; = logoUrl;
      organization.&lt;span class=&quot;hljs-property&quot;&gt;farmType&lt;/span&gt; = farmType;
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; baseOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;persistAndFlush&lt;/span&gt;(organization);
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Generate tenant ID from the organization name&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantId = name.&lt;span class=&quot;hljs-title function_&quot;&gt;toLowerCase&lt;/span&gt;().&lt;span class=&quot;hljs-title function_&quot;&gt;replace&lt;/span&gt;(&lt;span class=&quot;hljs-regexp&quot;&gt;/[^a-z0-9]/g&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;-&amp;#x27;&lt;/span&gt;);
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize the tenant database&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getTenantORM&lt;/span&gt;(tenantId);
      
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;201&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({
        ...organization,
        tenantId
      });
    } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;500&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt; });
    }
  });

  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; router;
};&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Tenant-Specific Routes&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/routes/cropRoutes.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Router&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;express&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;../entities/index.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { v4 &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; uuidv4 } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;uuid&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;createCropRoutes&lt;/span&gt; = (&lt;span class=&quot;hljs-params&quot;&gt;&lt;/span&gt;) =&amp;gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; router = &lt;span class=&quot;hljs-title class_&quot;&gt;Router&lt;/span&gt;();

  &lt;span class=&quot;hljs-comment&quot;&gt;// Get all crops for the current tenant&lt;/span&gt;
  router.&lt;span class=&quot;hljs-title function_&quot;&gt;get&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;req&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;, res) =&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantOrm = req.&lt;span class=&quot;hljs-property&quot;&gt;tenantORM&lt;/span&gt;;
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; crops = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;find&lt;/span&gt;(&lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;, {});
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;(crops);
    } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;500&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt; });
    }
  });

  &lt;span class=&quot;hljs-comment&quot;&gt;// Create a new crop&lt;/span&gt;
  router.&lt;span class=&quot;hljs-title function_&quot;&gt;post&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;req&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;, res) =&amp;gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; { name, plantingDate, organizationId } = req.&lt;span class=&quot;hljs-property&quot;&gt;body&lt;/span&gt;;
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (!name || !plantingDate || !organizationId) {
        &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;400&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Name, planting date, and organization ID are required&amp;#x27;&lt;/span&gt; });
      }
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantOrm = req.&lt;span class=&quot;hljs-property&quot;&gt;tenantORM&lt;/span&gt;;
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; crop = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Crop&lt;/span&gt;();
      crop.&lt;span class=&quot;hljs-property&quot;&gt;id&lt;/span&gt; = &lt;span class=&quot;hljs-title function_&quot;&gt;uuidv4&lt;/span&gt;();
      crop.&lt;span class=&quot;hljs-property&quot;&gt;name&lt;/span&gt; = name;
      crop.&lt;span class=&quot;hljs-property&quot;&gt;plantingDate&lt;/span&gt; = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Date&lt;/span&gt;(plantingDate);
      crop.&lt;span class=&quot;hljs-property&quot;&gt;organization&lt;/span&gt; = organizationId;
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;persistAndFlush&lt;/span&gt;(crop);
      
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;201&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;(crop);
    } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
      res.&lt;span class=&quot;hljs-title function_&quot;&gt;status&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;500&lt;/span&gt;).&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;message&lt;/span&gt;: error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt; });
    }
  });

  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; router;
};&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;How Migrations Work in Our Multi-Tenant System&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Creating Migrations&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For tenant-specific migrations, we have an npm script: &lt;code&gt;migrate:tenant:create&lt;/code&gt; which runs &lt;code&gt;mikro-orm migration:create --path ./src/migrations/tenant&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;This creates a migration file in &lt;code&gt;src/migrations/tenant/&lt;/code&gt; following MikroORM&amp;#39;s naming pattern (like &lt;code&gt;Migration20230621001_TestTenantMigration.ts&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Migration Application&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The system handles migrations in two places:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;a) &lt;strong&gt;TenantManager.getTenantORM()&lt;/strong&gt;: When a tenant&amp;#39;s ORM is initialized, it automatically runs migrations:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; migrator = orm.&lt;span class=&quot;hljs-title function_&quot;&gt;getMigrator&lt;/span&gt;();
  &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; migrator.&lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;();
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Migrations applied for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
} &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (error) { ... }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;b) &lt;strong&gt;index.ts&lt;/strong&gt;: The main application also runs migrations for the base database:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; migrator = orm.&lt;span class=&quot;hljs-title function_&quot;&gt;getMigrator&lt;/span&gt;();
  &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; migrator.&lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;();
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Migrations applied successfully&amp;#x27;&lt;/span&gt;);
} &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (error) { ... }&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Creating a Real Migration&lt;/strong&gt;:
To create a migration we can run the following:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npm run migrate:tenant:create -- --name AddFieldToTable&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will create a migration file like &lt;code&gt;Migration20231025001_AddFieldToTable.ts&lt;/code&gt; in &lt;code&gt;src/migrations/tenant/&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Then write your migration:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Migration&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/migrations&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Migration20231025001_AddFieldToTable&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;Migration&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;void&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;addSql&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;ALTER TABLE your_table ADD COLUMN new_field VARCHAR(255)&amp;#x27;&lt;/span&gt;);
  }

  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;down&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;void&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;addSql&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;ALTER TABLE your_table DROP COLUMN new_field&amp;#x27;&lt;/span&gt;);
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Applying to All Tenant DBs&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;test-migrations.ts&lt;/code&gt; script isn&amp;#39;t strictly necessary for normal migration operations, it&amp;#39;s more of a validation tool&lt;/li&gt;
&lt;li&gt;Migrations are automatically applied to each tenant DB when:&lt;ul&gt;
&lt;li&gt;A new request comes in and the tenant&amp;#39;s ORM is initialized for the first time&lt;/li&gt;
&lt;li&gt;The application starts and creates new tenants&lt;/li&gt;
&lt;li&gt;You manually run migrations using MikroORM CLI&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;For Consistent Application Across All Tenants&lt;/strong&gt;:
You have two options:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Let the system handle it naturally (migrations will apply when each tenant&amp;#39;s ORM is initialized)&lt;/li&gt;
&lt;li&gt;For immediate application across all tenants, you could run a script similar to &lt;code&gt;test-migrations.ts&lt;/code&gt; but focused on just applying migrations&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The beauty of this system is that migrations are handled automatically as part of the tenant ORM initialization. When you create a new tenant-specific migration, it will get applied the next time each tenant&amp;#39;s ORM is initialized.&lt;/p&gt;
&lt;h2&gt;Test Migration Scenario&lt;/h2&gt;
&lt;p&gt;Multi-tenant applications require careful handling of migrations to ensure schema changes are applied to all tenant databases. We&amp;#39;ll create a structure for both base and tenant-specific migrations:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/migrations/tenant/Migration20230621001_TestTenantMigration.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;Migration&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/migrations&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;export&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;Migration20230621001_TestTenantMigration&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;hljs-title class_ inherited__&quot;&gt;Migration&lt;/span&gt; {
  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;void&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;addSql&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;CREATE TABLE IF NOT EXISTS &amp;quot;migration_test&amp;quot; (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), test_name VARCHAR(255) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now())&amp;#x27;&lt;/span&gt;);
  }

  &lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;down&lt;/span&gt;(): &lt;span class=&quot;hljs-title class_&quot;&gt;Promise&lt;/span&gt;&amp;lt;&lt;span class=&quot;hljs-built_in&quot;&gt;void&lt;/span&gt;&amp;gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;addSql&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;DROP TABLE IF EXISTS &amp;quot;migration_test&amp;quot;&amp;#x27;&lt;/span&gt;);
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We&amp;#39;ll also create a utility to test that migrations work correctly across all tenant databases:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/test-migrations.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/core&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;PostgreSqlDriver&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;@mikro-orm/postgresql&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; baseOptions &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./config/mikro-orm.config.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./services/TenantManager.js&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;testTenantMigrations&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;&lt;/span&gt;) {
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Testing migrations for all tenant databases...&amp;#x27;&lt;/span&gt;);
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize base ORM&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; baseOrm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;MikroORM&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;init&lt;/span&gt;(baseOptions);
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; connection = baseOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getConnection&lt;/span&gt;();
  
  &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// Get a list of all tenant databases&lt;/span&gt;
    &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Retrieving list of tenant databases...&amp;#x27;&lt;/span&gt;);
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; results = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(
      &lt;span class=&quot;hljs-string&quot;&gt;`SELECT datname FROM pg_database WHERE datname LIKE &amp;#x27;tenant_%&amp;#x27;`&lt;/span&gt;
    );
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantDbs = results.&lt;span class=&quot;hljs-title function_&quot;&gt;map&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;(&lt;span class=&quot;hljs-params&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;row&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;&lt;/span&gt;) =&amp;gt;&lt;/span&gt; row.&lt;span class=&quot;hljs-property&quot;&gt;datname&lt;/span&gt;);
    &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Found &lt;span class=&quot;hljs-subst&quot;&gt;${tenantDbs.length}&lt;/span&gt; tenant databases: &lt;span class=&quot;hljs-subst&quot;&gt;${tenantDbs.join(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;, &amp;#x27;&lt;/span&gt;)}&lt;/span&gt;`&lt;/span&gt;);
    
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (tenantDbs.&lt;span class=&quot;hljs-property&quot;&gt;length&lt;/span&gt; === &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;) {
      &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;No tenant databases found. Creating a test tenant...&amp;#x27;&lt;/span&gt;);
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantId = &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;test_tenant&amp;#x27;&lt;/span&gt;;
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Create a test tenant&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`CREATE DATABASE tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
      &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Created test tenant database: tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
      
      &lt;span class=&quot;hljs-comment&quot;&gt;// Add to the list of tenants to test&lt;/span&gt;
      tenantDbs.&lt;span class=&quot;hljs-title function_&quot;&gt;push&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`tenant_&lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
    }
    
    &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize TenantManager&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantManager = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt;();
    
    &lt;span class=&quot;hljs-comment&quot;&gt;// Run migrations for each tenant&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; (&lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantDb &lt;span class=&quot;hljs-keyword&quot;&gt;of&lt;/span&gt; tenantDbs) {
      &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantId = tenantDb.&lt;span class=&quot;hljs-title function_&quot;&gt;replace&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;tenant_&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;#x27;&lt;/span&gt;);
      &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Testing migrations for tenant: &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
      
      &lt;span class=&quot;hljs-keyword&quot;&gt;try&lt;/span&gt; {
        &lt;span class=&quot;hljs-comment&quot;&gt;// Get tenant ORM and run migrations&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantOrm = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getTenantORM&lt;/span&gt;(tenantId);
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; migrator = tenantOrm.&lt;span class=&quot;hljs-title function_&quot;&gt;getMigrator&lt;/span&gt;();
        
        &lt;span class=&quot;hljs-comment&quot;&gt;// Run the migrations&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; executedMigrations = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; migrator.&lt;span class=&quot;hljs-title function_&quot;&gt;up&lt;/span&gt;();
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Executed &lt;span class=&quot;hljs-subst&quot;&gt;${executedMigrations.length}&lt;/span&gt; migrations for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
        
        &lt;span class=&quot;hljs-comment&quot;&gt;// Verify migration by checking if the test table exists&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; connection = tenantOrm.&lt;span class=&quot;hljs-property&quot;&gt;em&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;getConnection&lt;/span&gt;();
        &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tableExists = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(
          &lt;span class=&quot;hljs-string&quot;&gt;`SELECT to_regclass(&amp;#x27;migration_test&amp;#x27;) IS NOT NULL as exists`&lt;/span&gt;
        );
        
        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; (tableExists[&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;].&lt;span class=&quot;hljs-property&quot;&gt;exists&lt;/span&gt;) {
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`✅ Verification successful: &amp;#x27;migration_test&amp;#x27; table exists for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
          
          &lt;span class=&quot;hljs-comment&quot;&gt;// Insert a test record&lt;/span&gt;
          &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(
            &lt;span class=&quot;hljs-string&quot;&gt;`INSERT INTO migration_test (test_name) VALUES ($1)`&lt;/span&gt;,
            [&lt;span class=&quot;hljs-string&quot;&gt;`Test for &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt; at &lt;span class=&quot;hljs-subst&quot;&gt;${&lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;Date&lt;/span&gt;().toISOString()}&lt;/span&gt;`&lt;/span&gt;]
          );
          
          &lt;span class=&quot;hljs-comment&quot;&gt;// Check if record was inserted&lt;/span&gt;
          &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; records = &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; connection.&lt;span class=&quot;hljs-title function_&quot;&gt;execute&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`SELECT * FROM migration_test`&lt;/span&gt;);
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`✅ Inserted test record: `&lt;/span&gt;, records[&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;]);
        } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; {
          &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`❌ Verification failed: &amp;#x27;migration_test&amp;#x27; table does not exist for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;`&lt;/span&gt;);
        }
      } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
        &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`❌ Error testing migrations for tenant &lt;span class=&quot;hljs-subst&quot;&gt;${tenantId}&lt;/span&gt;:`&lt;/span&gt;, error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt;);
      }
    }
  } &lt;span class=&quot;hljs-keyword&quot;&gt;catch&lt;/span&gt; (&lt;span class=&quot;hljs-attr&quot;&gt;error&lt;/span&gt;: &lt;span class=&quot;hljs-built_in&quot;&gt;any&lt;/span&gt;) {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Error testing tenant migrations:&amp;#x27;&lt;/span&gt;, error.&lt;span class=&quot;hljs-property&quot;&gt;message&lt;/span&gt;);
  } &lt;span class=&quot;hljs-keyword&quot;&gt;finally&lt;/span&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// Clean up connections&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; baseOrm.&lt;span class=&quot;hljs-title function_&quot;&gt;close&lt;/span&gt;();
  }
}

&lt;span class=&quot;hljs-comment&quot;&gt;// Run the test&lt;/span&gt;
&lt;span class=&quot;hljs-title function_&quot;&gt;testTenantMigrations&lt;/span&gt;().&lt;span class=&quot;hljs-title function_&quot;&gt;catch&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;error&lt;/span&gt; =&amp;gt;&lt;/span&gt; {
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Unhandled error in migration test:&amp;#x27;&lt;/span&gt;, error);
  process.&lt;span class=&quot;hljs-title function_&quot;&gt;exit&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;);
}).&lt;span class=&quot;hljs-title function_&quot;&gt;then&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; {
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Migration test completed.&amp;#x27;&lt;/span&gt;);
  process.&lt;span class=&quot;hljs-title function_&quot;&gt;exit&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;);
});&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Main Application Setup&lt;/h2&gt;
&lt;p&gt;Now let&amp;#39;s tie everything together in our main application file:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// src/index.ts&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; express &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;express&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt; } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./services/TenantManager.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { tenantMiddleware } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./middleware/tenantMiddleware.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { createOrganizationRoutes } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./routes/organizationRoutes.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { createCropRoutes } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./routes/cropRoutes.js&amp;#x27;&lt;/span&gt;;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; { env } &lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;./config/env.js&amp;#x27;&lt;/span&gt;;

&lt;span class=&quot;hljs-keyword&quot;&gt;async&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;main&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;&lt;/span&gt;) {
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; app = &lt;span class=&quot;hljs-title function_&quot;&gt;express&lt;/span&gt;();
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(express.&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;());
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Initialize tenant manager&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;const&lt;/span&gt; tenantManager = &lt;span class=&quot;hljs-keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-title class_&quot;&gt;TenantManager&lt;/span&gt;();
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Base database must exist&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;getBaseORM&lt;/span&gt;();
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Routes not requiring tenant context&lt;/span&gt;
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/organizations&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;createOrganizationRoutes&lt;/span&gt;(tenantManager));
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Tenant-specific routes&lt;/span&gt;
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/api&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;tenantMiddleware&lt;/span&gt;(tenantManager));
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;use&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/api/crops&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;createCropRoutes&lt;/span&gt;());
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Health check endpoint&lt;/span&gt;
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;get&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;/health&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;(&lt;span class=&quot;hljs-params&quot;&gt;req, res&lt;/span&gt;) =&amp;gt;&lt;/span&gt; {
    res.&lt;span class=&quot;hljs-title function_&quot;&gt;json&lt;/span&gt;({ &lt;span class=&quot;hljs-attr&quot;&gt;status&lt;/span&gt;: &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;ok&amp;#x27;&lt;/span&gt; });
  });
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Start the server&lt;/span&gt;
  app.&lt;span class=&quot;hljs-title function_&quot;&gt;listen&lt;/span&gt;(env.&lt;span class=&quot;hljs-property&quot;&gt;PORT&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;() =&amp;gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;`Server running on port &lt;span class=&quot;hljs-subst&quot;&gt;${env.PORT}&lt;/span&gt;`&lt;/span&gt;);
  });
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// Handle graceful shutdown&lt;/span&gt;
  process.&lt;span class=&quot;hljs-title function_&quot;&gt;on&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;SIGTERM&amp;#x27;&lt;/span&gt;, &lt;span class=&quot;hljs-title function_&quot;&gt;async&lt;/span&gt; () =&amp;gt; {
    &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;log&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;SIGTERM received, shutting down...&amp;#x27;&lt;/span&gt;);
    &lt;span class=&quot;hljs-keyword&quot;&gt;await&lt;/span&gt; tenantManager.&lt;span class=&quot;hljs-title function_&quot;&gt;closeConnections&lt;/span&gt;();
    process.&lt;span class=&quot;hljs-title function_&quot;&gt;exit&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;);
  });
}

&lt;span class=&quot;hljs-title function_&quot;&gt;main&lt;/span&gt;().&lt;span class=&quot;hljs-title function_&quot;&gt;catch&lt;/span&gt;(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-params&quot;&gt;error&lt;/span&gt; =&amp;gt;&lt;/span&gt; {
  &lt;span class=&quot;hljs-variable language_&quot;&gt;console&lt;/span&gt;.&lt;span class=&quot;hljs-title function_&quot;&gt;error&lt;/span&gt;(&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Unhandled error in main:&amp;#x27;&lt;/span&gt;, error);
  process.&lt;span class=&quot;hljs-title function_&quot;&gt;exit&lt;/span&gt;(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;);
});&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Docker Setup&lt;/h2&gt;
&lt;p&gt;For easier deployment and development, let&amp;#39;s set up Docker:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-dockerfile&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# Dockerfile&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;FROM&lt;/span&gt; node:&lt;span class=&quot;hljs-number&quot;&gt;20&lt;/span&gt;-alpine

&lt;span class=&quot;hljs-keyword&quot;&gt;WORKDIR&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; /app&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;COPY&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; package*.json ./&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;RUN&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; npm install&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;COPY&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; . .&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;RUN&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; npm run build&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;CMD&lt;/span&gt;&lt;span class=&quot;language-bash&quot;&gt; [&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;node&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;dist/index.js&amp;quot;&lt;/span&gt;]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# docker-compose.yml&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;version:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;3.8&amp;#x27;&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;services:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;postgres:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;image:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;postgres:14&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;POSTGRES_USER:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;farmadmin&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;POSTGRES_PASSWORD:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;harvest2025&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;POSTGRES_DB:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;farm_tenants&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;ports:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;5432:5432&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;volumes:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;pgdata:/var/lib/postgresql/data&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;healthcheck:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;test:&lt;/span&gt; [&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;CMD-SHELL&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;pg_isready -U farmadmin -d farm_tenants&amp;quot;&lt;/span&gt;]
      &lt;span class=&quot;hljs-attr&quot;&gt;interval:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;10s&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;timeout:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;5s&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;retries:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;

  &lt;span class=&quot;hljs-attr&quot;&gt;app:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;build:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;.&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;ports:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;3000:3000&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;environment:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;NODE_ENV:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;development&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DB_HOST:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;postgres&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DB_PORT:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;5432&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DB_NAME:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;farm_tenants&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DB_USER:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;farmadmin&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;DB_PASSWORD:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;harvest2025&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;depends_on:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;postgres:&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;condition:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;service_healthy&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;volumes:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;pgdata:&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Using the Multi-Tenant Farm Management System&lt;/h2&gt;
&lt;p&gt;Let&amp;#39;s see how to use our multi-tenant system:&lt;/p&gt;
&lt;h3&gt;Create a New Farm Organization&lt;/h3&gt;
&lt;p&gt;To create a new farm organization and its corresponding tenant database:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl -X POST http://localhost:3000/organizations \
  -H &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Content-Type: application/json&amp;quot;&lt;/span&gt; \
  -d &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;{&amp;quot;name&amp;quot;: &amp;quot;Green Valley Co-op&amp;quot;, &amp;quot;farmType&amp;quot;: &amp;quot;mixed&amp;quot;, &amp;quot;logoUrl&amp;quot;: &amp;quot;https://example.com/logo.png&amp;quot;}&amp;#x27;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create an organization record in the base database&lt;/li&gt;
&lt;li&gt;Create a new tenant database named &lt;code&gt;tenant_green-valley-co-op&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Apply all tenant-specific migrations to the new database&lt;/li&gt;
&lt;li&gt;Return the organization details with its tenant ID&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Add Farm-Specific Data&lt;/h3&gt;
&lt;p&gt;To add data specific to a tenant (e.g., crops), include the tenant ID in the request:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl -X POST http://localhost:3000/api/crops \
  -H &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Content-Type: application/json&amp;quot;&lt;/span&gt; \
  -H &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;X-Tenant-ID: green-valley-co-op&amp;quot;&lt;/span&gt; \
  -d &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;{&amp;quot;name&amp;quot;: &amp;quot;Heirloom Tomatoes&amp;quot;, &amp;quot;plantingDate&amp;quot;: &amp;quot;2023-04-15&amp;quot;, &amp;quot;organizationId&amp;quot;: &amp;quot;the-org-uuid&amp;quot;}&amp;#x27;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The tenant middleware identifies the tenant from the &lt;code&gt;X-Tenant-ID&lt;/code&gt; header and routes the request to the appropriate tenant database.&lt;/p&gt;
&lt;h2&gt;Testing Your Multi-Tenant Setup&lt;/h2&gt;
&lt;p&gt;To ensure your multi-tenant system is working correctly, run the migration test:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npm run &lt;span class=&quot;hljs-built_in&quot;&gt;test&lt;/span&gt;:migrations&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Discover all existing tenant databases&lt;/li&gt;
&lt;li&gt;Apply any pending migrations to each tenant&lt;/li&gt;
&lt;li&gt;Verify that migrations executed successfully&lt;/li&gt;
&lt;li&gt;Create a test tenant if none exist&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Comparing Multi-Tenant Approaches&lt;/h2&gt;
&lt;p&gt;While we&amp;#39;ve implemented the database-per-tenant model in this tutorial, it&amp;#39;s worth understanding all three common approaches to multi-tenancy, as each has its own advantages:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Approach&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;th&gt;Pros&lt;/th&gt;
&lt;th&gt;Cons&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Database-per-Tenant&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Each tenant gets their own dedicated database&lt;/td&gt;
&lt;td&gt;• Maximum isolation&lt;br&gt;• Simplest compliance story&lt;br&gt;• Easy backup/restore per tenant&lt;br&gt;• Custom schema per tenant&lt;/td&gt;
&lt;td&gt;• More databases to manage&lt;br&gt;• Higher infrastructure costs&lt;br&gt;• Connection pooling challenges&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Schema-per-Tenant&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Each tenant gets their own schema within a shared database&lt;/td&gt;
&lt;td&gt;• Better isolation than row-level&lt;br&gt;• Easier compliance than row-level&lt;br&gt;• Lower infra cost than database-per-tenant&lt;br&gt;• Custom schema per tenant&lt;/td&gt;
&lt;td&gt;• DB-level resource contention&lt;br&gt;• More complex backup/restore&lt;br&gt;• Limited by DB schema count&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Row-Level Tenancy&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;All tenants share tables, rows filtered by tenant ID&lt;/td&gt;
&lt;td&gt;• Simplest to implement&lt;br&gt;• Lowest infrastructure cost&lt;br&gt;• Efficient resource sharing&lt;br&gt;• Easiest scaling&lt;/td&gt;
&lt;td&gt;• Weakest isolation&lt;br&gt;• Risk of data leaks&lt;br&gt;• Difficult compliance story&lt;br&gt;• Limited customization&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Choosing the right model depends on your specific requirements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Database-per-tenant&lt;/strong&gt; (as shown in this tutorial) works best when data isolation and regulatory compliance are top priorities, and when tenants might need custom schemas.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Schema-per-tenant&lt;/strong&gt; is a good middle ground that provides decent isolation at lower costs, but may not meet the strictest compliance requirements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Row-level tenancy&lt;/strong&gt; is ideal for applications with very large numbers of small tenants where cost-efficiency is the primary concern and data isolation requirements are minimal.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can also implement a hybrid approach, where some data uses row-level tenancy (for shared, non-sensitive data) while sensitive data is stored in tenant-specific schemas or databases.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Building multi-tenant applications presents unique challenges, but with the right architecture, you can create scalable, secure, and maintainable SaaS platforms. In this guide, we&amp;#39;ve built a robust multi-tenant farm management system using MikroORM and PostgreSQL that provides:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Complete data isolation&lt;/strong&gt; through the database-per-tenant model&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic tenant routing&lt;/strong&gt; via Express middleware&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient connection management&lt;/strong&gt; with our TenantManager service&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Automated tenant onboarding&lt;/strong&gt; with database creation and migrations&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Flexible API design&lt;/strong&gt; that separates tenant-specific and global endpoints&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This architecture gives you a solid foundation to build upon as your application grows. As you add more features, remember to keep tenant isolation as a core principle - every database query should be tenant-aware, either explicitly or implicitly through the middleware context. &lt;/p&gt;
&lt;p&gt;Future improvements to this setup could be to add authentication and session management.&lt;/p&gt;
&lt;p&gt;For production deployments, you&amp;#39;ll want to consider:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Implementing tenant caching&lt;/strong&gt; to reduce database lookups&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adding monitoring and observability&lt;/strong&gt; specific to multi-tenant metrics&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Creating tenant-aware rate limiting&lt;/strong&gt; to prevent noisy neighbors&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Establishing tenant lifecycle management&lt;/strong&gt; for suspensions, archiving, and deletions&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Setting up tenant-specific backups&lt;/strong&gt; for disaster recovery&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Further Resources&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mikro-orm.io/docs&quot;&gt;MikroORM Documentation&lt;/a&gt; - Official documentation for MikroORM&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mikro-orm.io/docs/usage-with-sql&quot;&gt;MikroORM PostgreSQL Integration&lt;/a&gt; - Specific guide for PostgreSQL&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://expressjs.com/&quot;&gt;Express.js Documentation&lt;/a&gt; - For more on Express and middleware&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Multi-tenancy enables your application to serve multiple customers efficiently while keeping their data secure and isolated. Whether you&amp;#39;re building a small SaaS startup or an enterprise platform, these principles will help you create scalable, maintainable software that can grow with your business.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;This tutorial demonstrates one approach to multi-tenancy with MikroORM. For different requirements, you might consider alternate approaches or technologies, but the core principles of tenant isolation and efficient resource management remain the same across implementations.&lt;/em&gt;&lt;/p&gt;
</content>
</entry>
<entry>
<title>in the woods</title>
<link href="https://spriggansecurity.com/blog/in-the-woods/"/>
<id>https://spriggansecurity.com/blog/in-the-woods/</id>
<published>2025-04-13T00:00:00.000Z</published>
<updated>2025-04-13T00:00:00.000Z</updated>
<category term="forest"/><category term="introspection"/>
<summary>Spent the evening in the mountain valley. The stream ran by swift and succulent as always in the spring. We have been building a lot in a short time there. I'm ready to…</summary>
<content type="html">&lt;p&gt;Spent the evening in the mountain valley. The stream ran by swift and succulent as always in the spring. We have been building a lot in a short time there. I&amp;#39;m ready to live on the property full time, but there always seems to be ebbs in flows in how much time and money allows. &lt;/p&gt;
&lt;p&gt;Regardless, it was a delight to get to watch the full moon rise over the mountain. The anticipation of it cresting over the trees is always palatable. &lt;/p&gt;
&lt;p&gt;There was good company and good food. It really was a nice cleanse from all the digital noise. Mixtures of the world feeling too chaotic, and the stillness inside of me has been unsettling. I don&amp;#39;t want to necessarily go hide under a rock, but the sentiment is not too far off. &lt;/p&gt;
&lt;h2&gt;in the works&lt;/h2&gt;
&lt;p&gt;The creative juices have started flowing. I have many projects in the works, and I would like to have the satisfaction of completing one. This is coming up. The Community Supported Agriculture app is nearly done. It is not going to be as easy as I was hoping to white label since I didn&amp;#39;t really understand the limits and powers of Remix. It wold be nice to build out a proper landing page and multi-tenant infrastructure to support the app. &lt;/p&gt;
&lt;p&gt;I think I will likely try and work on some lower lift stuff, and keep working on my smaller projects to build up to that. &lt;/p&gt;
&lt;p&gt;Overall in the past two years, there has been a lot of plates spinning, but the knowledge that has been harvested along the way is invaluable. There is less feelings of imposter syndrome. I do not necessarily do as much cybersecurity specific stuff during my job, but this doesn&amp;#39;t hold me back from sating my curiosity in my own time. &lt;/p&gt;
&lt;p&gt;Even though this blog is somewhat of a cheeky shot at making some CyberPunk thing. It&amp;#39;s mostly going to be a place to keep notes, and track some of my progress in my endeavors. A public journal feels like a good way to hold me accountable.&lt;/p&gt;
&lt;h3&gt;&lt;del&gt;Spriggan&lt;/del&gt;&lt;/h3&gt;
</content>
</entry>
<entry>
<title>github pages revamp plan</title>
<link href="https://spriggansecurity.com/blog/github-pages-revamp-plan/"/>
<id>https://spriggansecurity.com/blog/github-pages-revamp-plan/</id>
<published>2025-04-12T00:00:00.000Z</published>
<updated>2025-04-12T00:00:00.000Z</updated>
<category term="webdev"/><category term="nextjs"/>
<summary>This document outlines the steps that were taken to migrate the cyberpunk-blog project to the existing GitHub Pages repository (jaidenamari.github.io) while preserving…</summary>
<content type="html">&lt;h1&gt;GitHub Pages Migration Plan - COMPLETED ✅&lt;/h1&gt;
&lt;h2&gt;Overview&lt;/h2&gt;
&lt;p&gt;This document outlines the steps that were taken to migrate the cyberpunk-blog project to the existing GitHub Pages repository (&lt;code&gt;jaidenamari.github.io&lt;/code&gt;) while preserving both the new blog features and existing content/workflow.&lt;/p&gt;
&lt;p&gt;I wanted a fresh design using some of the new things I&amp;#39;ve been learning using next.js and radix ui. I&amp;#39;m still not convinced I like next.js, for anything complex, but it seems to be suitable for quickly standing up new designs. &lt;/p&gt;
&lt;p&gt;I don&amp;#39;t have any projects on my git that I can currently share with the public, but I will eventually get on documenting some of my coding projects as they come to fruition here. I&amp;#39;ll improve the aesthetic over time. I was curious about experimenting with the three.js library to add some 3d elements, but my first attempts are very shy of what I was hoping for, so I just added some basic animation for now.&lt;/p&gt;
&lt;h2&gt;Future Improvements&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Improve placeholder logo, add favicon.&lt;/li&gt;
&lt;li&gt;Actually implement three.js to create animated cyber forest and 3d stars in sky.&lt;/li&gt;
&lt;li&gt;Update colors to be a bit softer and more ephemeral, the effect on the page of moving particles should feel more spore like.&lt;/li&gt;
&lt;li&gt;Add projects from my github as I complete them&lt;/li&gt;
&lt;li&gt;Add notes and various study materials as I&amp;#39;m researching and learning about new cybersecurity, and dev concepts.&lt;/li&gt;
&lt;li&gt;Get some digital art made for blog posts, and Hero.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Current State&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;New cyberpunk-blog: Next.js project with modern aesthetics&lt;/li&gt;
&lt;li&gt;Existing blog: Hugo-based site with Obsidian workflow for content&lt;/li&gt;
&lt;li&gt;The existing blog has content in &lt;code&gt;content/posts/&lt;/code&gt; as markdown files with YAML frontmatter&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Migration Goals&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Preserve existing blog posts and content ✅&lt;/li&gt;
&lt;li&gt;Maintain Obsidian workflow for content creation ✅&lt;/li&gt;
&lt;li&gt;Update the aesthetics with the new cyberpunk forest design ✅&lt;/li&gt;
&lt;li&gt;Ensure a smooth transition without data loss ✅&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Step-by-Step Migration Plan&lt;/h2&gt;
&lt;h3&gt;Phase 1: Repository Setup ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Initialize git in the cyberpunk-blog project&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Create a new branch for the migration work&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Clone the existing GitHub Pages repo to a temporary location&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Analyze the current GitHub Pages repo structure&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 2: Content Integration ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Create a proper content directory structure in the cyberpunk-blog project&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Update the blog.ts file to read actual markdown files instead of mock data&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Copy existing blog posts from the GitHub Pages repo to the cyberpunk-blog project&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Ensure the frontmatter in the markdown files is compatible with the new system&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 3: Next.js Configuration for GitHub Pages ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Configure Next.js for static export (GitHub Pages requires static files)&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Add &lt;code&gt;output: &amp;#39;export&amp;#39;&lt;/code&gt; to the next.config.mjs file&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Configure basePath if needed (if the site will be at a subpath)&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Create a .nojekyll file to prevent GitHub Pages from processing with Jekyll&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Create a GitHub Actions workflow file for automated builds and deployments&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 4: Obsidian Workflow Integration ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Ensure the markdown parser can handle Obsidian-specific features&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Set up a content directory structure that works well with Obsidian&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Document the workflow for creating and editing content using Obsidian&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 5: Integration Testing ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Test the content rendering with existing blog posts&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Verify Obsidian workflow compatibility&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Test the build and export process&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Make necessary adjustments to styling and formatting&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 6: Deployment ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Add the GitHub Pages repo as a remote in the cyberpunk-blog project&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Push the changes to a new branch in the GitHub Pages repo&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Create a backup of the current GitHub Pages site&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Deploy to the main branch when everything is verified&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phase 7: Post-Deployment ✅&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Verify all content is accessible and correctly rendered&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Ensure the Obsidian workflow continues to function&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Update documentation for the new content management process&lt;/li&gt;
&lt;li&gt;&lt;input checked=&quot;&quot; disabled=&quot;&quot; type=&quot;checkbox&quot;&gt; Monitor for any issues&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Technical Implementation Details&lt;/h2&gt;
&lt;h3&gt;Content System Modifications&lt;/h3&gt;
&lt;p&gt;We modified &lt;code&gt;lib/blog.ts&lt;/code&gt; to:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Read markdown files from the file system ✅&lt;/li&gt;
&lt;li&gt;Parse frontmatter correctly ✅&lt;/li&gt;
&lt;li&gt;Support the existing YAML frontmatter format from Hugo ✅&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Required Dependencies&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;gray-matter&lt;/code&gt; for parsing frontmatter in markdown files ✅&lt;/li&gt;
&lt;li&gt;&lt;code&gt;fs&lt;/code&gt; for reading files from the filesystem ✅&lt;/li&gt;
&lt;li&gt;Already have &lt;code&gt;react-markdown&lt;/code&gt; for rendering ✅&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;GitHub Pages Configuration&lt;/h3&gt;
&lt;p&gt;GitHub Pages with Next.js requires:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Static HTML export ✅&lt;/li&gt;
&lt;li&gt;A .nojekyll file to prevent Jekyll processing ✅&lt;/li&gt;
&lt;li&gt;Proper asset path configuration ✅&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Rollback Plan&lt;/h2&gt;
&lt;p&gt;In case of critical issues:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Revert to the previous commit in the GitHub Pages repo&lt;/li&gt;
&lt;li&gt;Re-deploy the previous version&lt;/li&gt;
&lt;li&gt;Address issues in the cyberpunk-blog project before attempting migration again&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The migration from Hugo to Next.js was successfully completed. The new site maintains compatibility with the Obsidian workflow while providing a modern cyberpunk aesthetic. All existing content has been preserved, and the site is now deployed to GitHub Pages using GitHub Actions for automated deployment.&lt;/p&gt;
</content>
</entry>
<entry>
<title>blog post about setting up blogs</title>
<link href="https://spriggansecurity.com/blog/blog-post-about-setting-up-blogs/"/>
<id>https://spriggansecurity.com/blog/blog-post-about-setting-up-blogs/</id>
<published>2024-07-30T00:00:00.000Z</published>
<updated>2024-07-30T00:00:00.000Z</updated>
<category term="cybersecurity"/><category term="blogging"/>
<summary>I created a new github account, mainly because I wanted to rebrand my online presence and to have a clear trackable start. While my old git has 1000's of commits, it's…</summary>
<content type="html">&lt;h3&gt;1. Create a Github Account&lt;/h3&gt;
&lt;p&gt;I created a new github account, mainly because I wanted to rebrand my online presence and to have a clear trackable start. While my old git has 1000&amp;#39;s of commits, it&amp;#39;s mainly to internal work projects. &lt;/p&gt;
&lt;h3&gt;2. Create a New Repository&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Log into GitHub.&lt;/li&gt;
&lt;li&gt;Click on the &amp;quot;+&amp;quot; icon in the top right corner and select &amp;quot;New repository&amp;quot;.&lt;/li&gt;
&lt;li&gt;I&amp;#39;ll name my repository as &lt;code&gt;spriggan.github.io&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set the repository to &amp;quot;Public&amp;quot; and click &amp;quot;Create repository&amp;quot;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;3. Set Up GitHub Pages&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;I&amp;#39;ll navigate to my new repository.&lt;/li&gt;
&lt;li&gt;Click on the &amp;quot;Settings&amp;quot; tab.&lt;/li&gt;
&lt;li&gt;In the left-hand pane, I&amp;#39;ll click on &amp;quot;Pages&amp;quot;.&lt;/li&gt;
&lt;li&gt;Under &amp;quot;Source&amp;quot;, I&amp;#39;ll select deploy from branch to start, but may want to customize this with github actions eventually I can select which branch to service this from &amp;quot;main&amp;quot; works for now.
&lt;a href=&quot;https://docs.github.com/en/pages/quickstart&quot;&gt;https://docs.github.com/en/pages/quickstart&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;4. Install Hugo Locally&lt;/h3&gt;
&lt;p&gt;I decided to use hugo instead, because I liked the feel of Malware Hell by C3RB3RU5 on their github. They are using the LoveIt Theme which is Hugo in order to run the blog:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/dillonzq/LoveIt/tree/e9e89a4613baee823596822b7d246f5931263491&quot;&gt;https://github.com/dillonzq/LoveIt/tree/e9e89a4613baee823596822b7d246f5931263491&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://c3rb3ru5d3d53c.github.io/categories/docs/&quot;&gt;https://c3rb3ru5d3d53c.github.io/categories/docs/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now I had initially setup the blog to use jekyll and there were some trials and tribulations to switching over. I&amp;#39;m always learning new things in git, and managed to stumble my way into resetting up the project from scratch.&lt;/p&gt;
&lt;p&gt;I also had to add the .nojekyll file to my repo otherwise it tried to build the project using Jekyll in Github Actions.&lt;/p&gt;
&lt;p&gt;I wanted to customize my blog locally before pushing changes to GitHub:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Install hugo &lt;code&gt;brew install hugo&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Remove the Jekyll version of the blog by simply running&lt;/li&gt;
&lt;li&gt;Create a new Hugo site.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;	hugo new site spriggan.github.io
	&lt;span class=&quot;hljs-built_in&quot;&gt;cd&lt;/span&gt; spriggan.github.io&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5. Customize My Hugo Site&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;I&amp;#39;ll clone the LoveIt Theme to my repo&lt;/p&gt;
&lt;p&gt; &lt;code&gt;git init&lt;/code&gt;
 &lt;code&gt;git submodule add https://github.com/dillonzq/LoveIt.git themes/LoveIt&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Once added I modified the hugo.toml file.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Basic Config (This got more advanced as I dove down the rabbit hole, but I started with c3rb3rusd3d53c&amp;#39;s config):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;baseURL = &amp;quot;https://jaidenamari.github.io/&amp;quot;  
languageCode = &amp;quot;en&amp;quot;  
title = &amp;quot;My Cybersecurity Adventure&amp;quot;  
description = &amp;quot;Where cyber witchery meets security&amp;quot;  
theme = &amp;quot;LoveIt&amp;quot;  
publishDir = &amp;quot;docs&amp;quot;  
  
[params]  
  version = &amp;quot;0.2.X&amp;quot;  
  
[menu]  
  [[menu.main]]  
    identifier = &amp;quot;posts&amp;quot;  
    name = &amp;quot;Posts&amp;quot;  
    url = &amp;quot;/posts/&amp;quot;  
    weight = 1  
  [[menu.main]]  
    identifier = &amp;quot;tags&amp;quot;  
    name = &amp;quot;Tags&amp;quot;  
    url = &amp;quot;/tags/&amp;quot;  
    weight = 2  
  [[menu.main]]  
    identifier = &amp;quot;categories&amp;quot;  
    name = &amp;quot;Categories&amp;quot;  
    url = &amp;quot;/categories/&amp;quot;  
    weight = 3&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Eventually I will work on a more custom theme. I want to emulate the &lt;a href=&quot;https://github.com/SakuraIsayeki/vanilla-amoled-theme&quot;&gt;Vanilla Amoled&lt;/a&gt;  theme I use in Obsidian. In addition to this &amp;quot;ultra-dark&amp;quot; theme I will add some pops of color eventually to break things up visually. &lt;/p&gt;
&lt;h3&gt;6. Set Up Continuous Integration (CI) with GitHub Actions&lt;/h3&gt;
&lt;p&gt;I&amp;#39;ll create a &lt;code&gt;.github/workflows&lt;/code&gt; directory in my repository. I used the gitub pages repo from peaceiris on github: &lt;a href=&quot;https://github.com/peaceiris/actions-gh-pages&quot;&gt;https://github.com/peaceiris/actions-gh-pages&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;This was a bit tricky to setup because I tried switching my github pages settings to deploy using github actions, but later found that this caused problems with the GITHUB_TOKEN, which was an issue mentioned in the peaceiris repo FAQ. Instead I opted to just deploy from the gh-pages branch that was included in my repo after hugo builds the &lt;code&gt;./public&lt;/code&gt; folder.&lt;/p&gt;
&lt;h3&gt;7. Import Obsidian Notes&lt;/h3&gt;
&lt;p&gt;I&amp;#39;ll create a new vault - or a folder in my current vault - for the blog.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;I opted to open the content folder of the blog as a new vault, then imported all my themes by copying the .obsidian hidden folder from my personal vault. This transferred all my stypes and fonts to the new vault. &lt;/li&gt;
&lt;li&gt;.gitignore now has .obsidian in it so that my configs are not includes.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;By following these steps, I&amp;#39;ll have a fully functional blog hosted on GitHub Pages, using Jekyll to manage my content. This setup is not only free but also leverages my existing skills in web development and Markdown.&lt;/p&gt;
&lt;h3&gt;8. Write My First Blog Post&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;I&amp;#39;ll navigate to the &lt;code&gt;content/posts&lt;/code&gt; directory in the repository.&lt;/li&gt;
&lt;li&gt;Create a new Markdown file named hello-moon.md`.&lt;/li&gt;
&lt;li&gt;Add the following front matter to the top...or on second thought make a &lt;code&gt;/templates&lt;/code&gt; folder, and make the following into a template called post template. It&amp;#39;s important that the &lt;code&gt;---&lt;/code&gt; delimeter doesn&amp;#39;t have spaces.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-markdown&quot;&gt;---
title: &amp;quot;{{title}}&amp;quot;
date: {{date}}
draft: false
tags: [&amp;quot;cybersecurity&amp;quot;, &amp;quot;blogging&amp;quot;]
&lt;span class=&quot;hljs-section&quot;&gt;categories: [&amp;quot;blog&amp;quot;]
---&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&quot;2&quot;&gt;
&lt;li&gt;Use &lt;code&gt;cmd + p&lt;/code&gt; to open the command pallete on macOS&lt;/li&gt;
&lt;li&gt;Insert the template by typing &lt;code&gt;Templates: Insert template&lt;/code&gt; then choose &lt;code&gt;Post Template&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Commit and push my changes to GitHub.&lt;/li&gt;
&lt;/ol&gt;
</content>
</entry>
<entry>
<title>hello moon</title>
<link href="https://spriggansecurity.com/blog/hello-moon/"/>
<id>https://spriggansecurity.com/blog/hello-moon/</id>
<published>2024-07-26T12:00:00.000Z</published>
<updated>2024-07-26T12:00:00.000Z</updated>
<category term="cybersecurity"/><category term="journey"/>
<summary>Trying something new. Documenting what I do.</summary>
<content type="html">&lt;p&gt;Trying something new. Documenting what I do. &lt;/p&gt;
&lt;p&gt;A blog to document my adventures in the technical, the liminal, the ephemeral, the phantasmagoric, and what have you.&lt;/p&gt;
&lt;p&gt;I&amp;#39;m a professional, but also a human. I have the need to create emote and play. Not everything we do that is technical and professional needs to be serious. Technical writing is the bran flakes of experiences it&amp;#39;s plain, its dry, it does good work. But in a world quickly adapting AI to every possible situation there needs to be some succulent flavors and dynamics in writing that offset the 1..2..3 mentality. &lt;/p&gt;
</content>
</entry>
</feed>
