<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Walid Karray on Medium]]></title>
        <description><![CDATA[Stories by Walid Karray on Medium]]></description>
        <link>https://medium.com/@walid.karray?source=rss-aaefb44882c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N2DmWRuCOoPoic4zauFvFQ.jpeg</url>
            <title>Stories by Walid Karray on Medium</title>
            <link>https://medium.com/@walid.karray?source=rss-aaefb44882c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:21:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@walid.karray/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Got Tired of aws sso login. So I Built a Terminal Dashboard That Never Lets My Credentials Die]]></title>
            <link>https://medium.com/@walid.karray/i-got-tired-of-aws-sso-login-so-i-built-a-terminal-dashboard-that-never-lets-my-credentials-die-162094343a03?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/162094343a03</guid>
            <category><![CDATA[aws-sso]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 10:22:31 GMT</pubDate>
            <atom:updated>2026-06-12T10:22:31.819Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A fast, single-process TUI that keeps your AWS SSO credentials fresh — automatically — while it’s open.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GFNhZp1dNIv-n5hpOcmOg.png" /></figure><h3>The 4:55 PM problem</h3><p>It’s late afternoon. A deploy is halfway out the door. The pipeline stops dead:</p><pre>An error occurred (ExpiredToken) when calling the AssumeRole operation:<br>The security token included in the request is expired.</pre><p>I know exactly what’s happened, because it happens to me twice a week. My AWS SSO token quietly expired. Now I get to run the ritual:</p><pre>aws sso login --profile acme-prod-admin</pre><p>A browser tab fires open. I click “Confirm and continue.” I click “Allow.” I go back to the terminal. I re-run the deploy. It works — until the <em>next</em> token expires.</p><p>Multiply that by <strong>a dozen profiles</strong> across prod, staging, a data platform, and a couple of sandbox accounts, and you get the real problem: I had no idea, at any given moment, <strong>which credentials were still alive and which were about to die.</strong> ~/.aws/config is a wall of text. The AWS CLI tells you nothing until something is already broken. So I&#39;d either log in to <em>everything</em> &quot;just in case&quot; (a dozen browser dances) or get surprised mid-task. Both are terrible.</p><p>I wanted a single screen that showed me every profile, its live status, and how long until it expired — and that would quietly keep the profiles I actually use topped up. So I built it.</p><p>It’s called <strong>awssesh</strong>. npx awssesh, and you&#39;re in.</p><h3>One screen, everything at a glance</h3><p>awssesh opens straight into a <strong>k9s-style, list-first dashboard</strong> (that’s the screen up top). No menus to dig through — every SSO profile from your ~/.aws/config, with a live status and an expiry countdown, the moment it launches.</p><ul><li>🟢 <strong>valid</strong> — credentials are good; the EXPIRES column counts down (58m, 7m…).</li><li>⚠️ <strong>needs-login</strong> — this session needs an interactive browser login.</li><li><strong>⟳</strong> next to a profile means it’s <em>pinned</em> for auto-refresh (more on that below).</li></ul><p>Move with ↑/↓ or j/k. That&#39;s the whole mental model. The thing I most wanted — <em>&quot;which of these is about to break?&quot;</em> — is now answered in one glance instead of a guess.</p><p>When the list gets long, hit / and filter by name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vXt1B0BiWIlXTysJkYYCQ.png" /></figure><p>Press Enter on any profile to see the full picture — account ID, role, region, exact expiry, and the SSO start URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3c60J1vG7X7YanKZ1AYO8g.png" /></figure><h3>The part that actually fixed my life: auto-refresh</h3><p>Here’s the feature that turned awssesh from “nice list” into “I never think about this anymore.”</p><p>Navigate to a profile you care about and press a. That pins it with a <strong>⟳</strong> marker. From then on, <em>while the dashboard is open</em>, awssesh watches that profile&#39;s role-credential expiry and refreshes it <strong>just before it would expire</strong> — by default, within a 5-minute lead window.</p><p>No fixed-interval polling hammering AWS every 30 seconds. No wasted refreshes. It looks at the actual expiry timestamp and acts only when it needs to. The credentials for my pinned prod and data-warehouse profiles are simply <em>always ready</em> when I reach for them.</p><p>And when a refresh genuinely requires me — i.e. the underlying SSO session needs a fresh browser login — awssesh doesn’t fail silently and it doesn’t nag. It sends a <strong>desktop notification</strong>:</p><pre>awssesh: acme-prod-admin needs login</pre><p>…and drops me into a clean device-login screen where I can copy the URL or open the browser in one keystroke:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6b3JAmAdphfOOmj2gS4Pvg.png" /></figure><p>The result: I get the <em>convenience</em> of background refreshing without an actual background daemon lurking on my machine. awssesh is <strong>a single process</strong> — when you press q, it&#39;s gone. Nothing to manage, nothing to leak, nothing left running after you close it.</p><p>You can tune the behavior in Settings (s) — toggle notifications and set the refresh lead time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKjlMCpgTmA_Js9YwO7SuA.png" /></figure><h3>One keystroke for everything else</h3><p>The whole point of a TUI is that you never leave the keyboard. From the dashboard:</p><p>KeyActionaToggle ⟳ auto-refresh (pin/unpin)rRefresh the current profile nowcCopy export AWS_* env vars to clipboardyCopy the profile nameoOpen the AWS console in your browser/Filter profilessSettings · q Quit</p><p>That c shortcut is the one I use constantly — it copies a ready-to-paste block of export AWS_ACCESS_KEY_ID=… AWS_SECRET_ACCESS_KEY=… AWS_SESSION_TOKEN=… for the selected profile.</p><p>And here’s the move that replaced aws sso login in my muscle memory completely. awssesh ships a few non-interactive subcommands too, including export:</p><pre># Inject a profile&#39;s credentials straight into your current shell<br>eval $(awssesh export prod)</pre><p>No copy-paste, no browser, no TUI even — the credentials are just <em>in your shell</em>. There’s also awssesh status to print everything and exit (great for scripts), and awssesh refresh [profile] to top one up — or all your pinned profiles — on demand.</p><p>See it all together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJfDckMbLokhZmvFbhGpqw.gif" /></figure><h3>Try it in 10 seconds</h3><p>If you already have <strong>AWS CLI v2</strong> configured with SSO profiles in ~/.aws/config, there&#39;s nothing else to set up:</p><pre># Run it without installing anything<br>npx awssesh</pre><pre># ...or with Bun<br>bunx awssesh</pre><pre># ...or install it globally<br>npm install -g awssesh</pre><p>That’s the entire onboarding. It reads your existing config, shows you the dashboard, and you pin what you care about.</p><h3>Why I built it this way</h3><p>I had earlier versions of this idea that were <em>more</em> clever — background daemons, an embedded web dashboard, the works. I threw all of it out. What I actually wanted, every single day, was dead simple: <strong>one screen that tells me the truth about my credentials, keeps the important ones alive while I’m working, and gets out of the way when I quit.</strong></p><p>That’s awssesh. It’s free, open-source (MIT), and built with Bun + React + Ink.</p><ul><li>⭐ <strong>GitHub:</strong> <a href="https://github.com/tux86/awssesh">github.com/tux86/awssesh</a></li><li>📦 <strong>npm:</strong> <a href="https://www.npmjs.com/package/awssesh">npmjs.com/package/awssesh</a></li></ul><p>If AWS SSO tokens have ever blown up a deploy at 4:55 PM, give it a npx awssesh. And if it saves you a browser dance or two, a star on the repo means a lot.</p><p><em>Made with ❤️ by </em><a href="https://github.com/tux86"><em>tux86</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162094343a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ This CLI Tool Solved My AWS SSO Credentials Nightmare (DEPRECATED)]]></title>
            <link>https://medium.com/@walid.karray/this-cli-tool-solved-my-aws-sso-credentials-nightmare-b89b03bed097?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89b03bed097</guid>
            <category><![CDATA[aws-sso]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 20:59:31 GMT</pubDate>
            <atom:updated>2026-06-12T10:27:02.703Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Update (June 2026): This tool has evolved a lot and is now awssesh — simpler, faster, npm-installable. 👉 </strong><a href="https://medium.com/@walid.karray/i-got-tired-of-aws-sso-login-so-i-built-a-terminal-dashboard-that-never-lets-my-credentials-die-162094343a03"><strong>Read the current version here.</strong></a></p><blockquote>Every day, same story. 😤 Tokens expire. Deploys break at the worst possible time. I’m running aws sso login five times a day across 10+ AWS accounts, juggling browser tabs and verification codes — all while trying to actually get work done.</blockquote><p>I couldn’t find a tool that handled this properly. So I built one. 🛠️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8EvWwPsHHxocId3bSQ8zA.gif" /></figure><h3>😩 The Daily Pain</h3><p>If you manage multiple AWS accounts through SSO, you already know this pain intimately:</p><p>🔁 Open terminal. Run a command. Open browser. Enter code. Wait. Repeat. ❓ No idea which profiles are still valid and which expired an hour ago. 💥 A deploy breaks silently because a token expired mid-way. 🚫 No dashboard. No bulk operations. Just one profile at a time, manually.</p><p>The AWS CLI gives you aws sso login — profile my-profile. One profile. One at a time. Every. Single. Time. ⏳</p><p>After months of this frustration, I decided to build the tool I always wished existed — and that’s how SSOmatic was born. 🚀</p><h3>⚡ What SSOmatic Does</h3><p>SSOmatic is a single CLI tool that auto-discovers every SSO profile in your ~/.aws/config and gives you a live status dashboard — instantly. No configuration files. No setup steps. Just run it and see everything at a glance.</p><p>On first launch, it scans your config, finds all your profiles — including sso-session blocks — and shows you exactly what’s valid, what’s expired, and what needs attention. 🟢 Green dot means you’re good. 🔴 Red dot means it’s time to refresh. Simple as that.</p><h3>🔄 Bulk Refresh Changed Everything</h3><p>This is the feature that genuinely saved my sanity. Select the profiles you want, hit Enter, and SSOmatic handles the entire SSO device auth flow for each one — token polling, caching, credential writing. You just approve in the browser. That’s it. ✅</p><p>I also added a favorites system — so your most-used profiles are always pre-selected. One keystroke to refresh everything you need for the day. ⭐</p><h3>👻 The Daemon That Runs in the Background</h3><p>This is the real game-changer. Set a refresh interval — 15 minutes, 30 minutes, whatever fits your workflow — pick your profiles, and SSOmatic silently keeps them alive in the background. It refreshes tokens before they expire and sends desktop notifications when something needs your manual attention. 🔔</p><p>No more mid-deploy surprises. No more “which profile expired?” guessing games. Just peace of mind. 😌</p><h3>🌐 Press W, Get a Web Dashboard</h3><p>This is the feature I’m most proud of. While building the CLI, I realized that sometimes I just want a browser tab I can glance at without switching context. So I embedded a web server directly into the CLI — no extra process, no separate install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFmkKPZMe62k0pEUUOgOwQ.gif" /></figure><p><strong>Press w in the terminal. A sleek dark-mode web dashboard spins up on localhost instantly. Same data, same profiles, same live status — just beautifully rendered in React with Tailwind. Press w again and the server stops. 🎨</strong></p><p>One binary. Two interfaces. Your preference is remembered too — next time you launch SSOmatic, the web server starts automatically if you had it on before. 💡</p><h3>🛠️ The Technical Side</h3><p>For those who want to peek under the hood — here’s the stack:</p><p>⚡ Bun as the runtime — blazing-fast startup and single binary compilation. 🖥️ React + Ink for the terminal UI — yes, actual React, in the terminal. 🌐 React + Vite + Tailwind for the web dashboard. 💪 TypeScript everywhere. 🔗 The web server is a Bun HTTP server with a simple RPC bridge to the same credential logic the CLI uses.</p><p>The whole project is a flat, single-package structure. No monorepo madness. No workspace complexity. One entry point, one build command. Clean and simple. 🧹</p><h3>🌍 It’s Open Source</h3><p>I built SSOmatic to scratch my own itch — but if you’re dealing with the same AWS SSO pain, I’d love for you to give it a try. It’s free, open source, and actively maintained.</p><p><strong>💻 Install via Homebrew (macOS / Linux):</strong></p><pre>brew install tux86/tap/ssomatic</pre><p><strong>GitHub: </strong><a href="https://github.com/tux86/ssomatic"><strong>https://github.com/tux86/ssomatic</strong></a></p><p>Install it, fire up bun run start, and let me know what you think. Issues, feedback, and PRs are all very welcome — I read everything. 🙌</p><p>If you work with AWS SSO across multiple accounts and this resonates with you, share it with your team. Chances are they’re suffering through the exact same manual refresh cycle — and they’ll thank you for it. 💬</p><p><strong>#AWS #DevTools #OpenSource #CLI #TypeScript #Bun #CloudEngineering #DevOps</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89b03bed097" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Stopped Paying for Time-Tracking SaaS and Built Presto Instead]]></title>
            <link>https://medium.com/@walid.karray/why-i-stopped-paying-for-time-tracking-saas-and-built-presto-instead-bb5497b5b2c9?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb5497b5b2c9</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 21:23:32 GMT</pubDate>
            <atom:updated>2026-03-05T21:23:32.724Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re a freelancer. You track billable days. You send activity reports to clients. Why does your tooling feel like it was built for a 500-person company?</p><p>Most time-tracking apps are designed for teams, managers, and enterprise workflows. They come with seat-based pricing, bloated dashboards, and features you’ll never touch. All you need is a clean monthly report showing which days you worked — and maybe a PDF to attach to your invoice.</p><p>That’s exactly what <strong>Presto</strong> does. Nothing more, nothing less.</p><h3>What Is Presto?</h3><p><a href="https://github.com/tux86/presto">Presto</a> is an open-source, self-hosted activity report generator. It lets you:</p><ul><li>Track billable days per client and mission on a <strong>visual calendar</strong></li><li>Generate <strong>professional PDF reports</strong> ready to send to clients</li><li>Monitor your <strong>revenue and utilization</strong> with built-in dashboards</li><li>Run it on <strong>your own server</strong> with a single Docker command</li></ul><p>It’s MIT-licensed, fully self-contained, and takes under 2 minutes to deploy.</p><h3>The Dashboard: Your Year at a Glance</h3><p>When you open Presto, the first thing you see is your <strong>activity dashboard</strong> — a card-based overview of all your reports for the year, grouped by client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvYUGLbA_1LyJ737DS2QbQ.png" /><figcaption>Presto Dashboard — Activity report cards grouped by client, with calendar previews and revenue</figcaption></figure><p>Each card shows the month, mission name, a <strong>mini calendar preview</strong> (so you can visually spot worked days), the number of days billed, and the revenue. Reports are color-coded by client and tagged as Draft or Validated.</p><p>You can <strong>filter by company or client</strong>, navigate between years, and create a new report in two clicks.</p><p>No clutter. No Gantt charts. Just your work, organized by month.</p><h3>The Report Editor: Click, Fill, Done</h3><p>The heart of Presto is the <strong>calendar-based report editor</strong>. Each day in the month is a clickable cell — tap once for a full day, tap again for a half day, tap again to clear it. That’s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIcA60Qre87zfPjuiOJdDw.png" /><figcaption>Presto Activity Report Editor — Calendar view with full days, half days, and holiday markers</figcaption></figure><p>The side panel shows you a live summary: days worked out of available workdays, your daily rate, and the total amount. When a report is complete, toggle it to <strong>Validated</strong> and hit <strong>Export PDF</strong> to generate a print-ready document.</p><h3>Features that save real time:</h3><ul><li><strong>Auto-fill workdays</strong> — One click fills every weekday in the month. Weekends and public holidays are automatically skipped.</li><li><strong>Country-specific holidays</strong> — Set a holiday country per client (France, Germany, Luxembourg… all countries supported). Holidays appear as yellow dots on the calendar.</li><li><strong>Half-day precision</strong> — Because sometimes you only work a morning.</li><li><strong>Notes per day</strong> — Add context to specific days (meetings, deliveries, on-site visits).</li><li><strong>Draft / Validated workflow</strong> — Validated reports are locked. No accidental edits.</li></ul><h3>Reporting: Know Your Numbers</h3><p>The <strong>Reporting</strong> page gives you a high-level view of your freelance business for the year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MGxF5WREGBNG8qAZWke6g.png" /><figcaption>Presto Reporting Dashboard — KPIs, revenue charts, and utilization gauge</figcaption></figure><p>Four KPI cards at the top:</p><ul><li><strong>Days Worked</strong> — with year-over-year comparison and a sparkline trend</li><li><strong>Revenue</strong> — total revenue with automatic multi-currency conversion</li><li><strong>Active Clients</strong> — how many clients you billed this year</li><li><strong>Utilization</strong> — a gauge showing what percentage of available working days you actually billed</li></ul><p>Below that, interactive charts break down <strong>revenue by client</strong> (stacked bar), <strong>client distribution</strong> (donut), and monthly trends for both revenue and days.</p><p>If you work with clients in different currencies (EUR, USD, GBP…), Presto automatically converts everything to your <strong>base currency</strong> using live exchange rates. You see one unified number.</p><h3>PDF Export: Professional Reports in Seconds</h3><p>When a report is validated, Presto generates a <strong>server-side PDF</strong> using React PDF. The output includes:</p><ul><li>Your company details and client information</li><li>A clean calendar grid with worked days highlighted</li><li>Totals: days worked, daily rate, total amount</li><li>Notes section</li><li>Available in <strong>5 languages</strong>: English, French, German, Spanish, Portuguese</li></ul><p>The filename is auto-generated (e.g., Acme_Corp-API_Project-2025-12.pdf). Download, attach to your invoice email, done.</p><h3>Multi-Client, Multi-Currency, Multi-Language</h3><p>Presto is built for freelancers who juggle multiple clients across borders:</p><ul><li><strong>Companies</strong> — Register your own legal entities (useful if you operate under multiple business names)</li><li><strong>Clients</strong> — Each client gets its own currency, holiday country, color, and contact details</li><li><strong>Missions</strong> — Each mission (project/contract) has a daily rate and links to a client</li><li><strong>Currencies</strong> — All ISO 4217 currencies supported. Revenue dashboards convert automatically.</li><li><strong>Languages</strong> — Full UI in English, French, German, Spanish, and Portuguese</li></ul><h3>Deploy in 60 Seconds</h3><p>Presto ships as a <strong>single Docker image</strong>. No microservices, no separate frontend container, no Redis, no message queue. Just the app and PostgreSQL.</p><pre># docker-compose.yml<br>services:<br>  presto:<br>    image: axforge/presto:latest<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      DATABASE_URL: postgresql://presto:secret@db:5432/presto<br>      JWT_SECRET: your-secret-key-min-32-characters-long<br>    depends_on:<br>      - db<br><br>  db:<br>    image: postgres:17-alpine<br>    environment:<br>      POSTGRES_USER: presto<br>      POSTGRES_PASSWORD: secret<br>      POSTGRES_DB: presto<br>    volumes:<br>      - pgdata:/var/lib/postgresql/data<br><br>volumes:<br>  pgdata:</pre><pre>docker compose up -d</pre><p>Open http://localhost:8080, create an account, and start tracking.</p><h3>Single-user mode</h3><p>If you’re the only user, skip authentication entirely:</p><pre>environment:<br>  AUTH_DISABLED: &quot;true&quot;</pre><p>No login screen. No password. Just open the app and go.</p><h3>Lock it down after setup</h3><p>Created your account? Disable registration so nobody else can sign up:</p><pre>environment:<br>  REGISTRATION_ENABLED: &quot;false&quot;</pre><h3>The Tech Behind It</h3><p>For the curious:</p><ul><li><strong>Runtime</strong> — Bun</li><li><strong>Frontend</strong> — React 19, Vite 6, Tailwind CSS 4, Zustand, TanStack Query</li><li><strong>Backend</strong> — Hono, Drizzle ORM</li><li><strong>Database</strong> — PostgreSQL</li><li><strong>PDF</strong> — @react-pdf/renderer (server-side)</li><li><strong>Language</strong> — TypeScript 5.7, strict mode</li><li><strong>Tests</strong> — 222 API E2E tests</li></ul><p>Migrations run automatically at startup. The Docker image is a multi-stage build that produces a lean Alpine-based container.</p><h3>Who Is Presto For?</h3><p>Presto is for <strong>freelancers and independent consultants</strong> who:</p><ul><li>Bill clients by the day (or half-day)</li><li>Need to submit monthly activity reports</li><li>Want to track revenue across multiple clients and currencies</li><li>Prefer self-hosted tools over SaaS subscriptions</li><li>Value simplicity over feature bloat</li></ul><p>If you’ve been using spreadsheets, Notion templates, or overpriced time trackers to do what is fundamentally a simple task — Presto is your exit ramp.</p><h3>Get Started</h3><ul><li><strong>GitHub</strong>: <a href="https://github.com/tux86/presto">github.com/tux86/presto</a></li><li><strong>Docker Hub</strong>: <a href="https://hub.docker.com/r/axforge/presto">hub.docker.com/r/axforge/presto</a></li><li><strong>License</strong>: MIT — free forever, no strings attached</li></ul><p>Star the repo if you find it useful. Contributions and feedback are welcome.</p><p><em>Presto is open-source and actively maintained. Built by a freelancer, for freelancers.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb5497b5b2c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Guide: Automating Tailscale Certificate Configuration on Synology DSM]]></title>
            <link>https://medium.com/@walid.karray/automating-tailscale-certificate-configuration-on-synology-dsm-8a3c3b79e010?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a3c3b79e010</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[synology]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[dsm]]></category>
            <category><![CDATA[tailscale]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 22:32:22 GMT</pubDate>
            <atom:updated>2024-08-11T19:33:09.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLY56dVBX6AdXzG2m3n3HA.png" /></figure><blockquote><strong>Important Update (11 Aug 2024):</strong> The solution outlined in this article is now outdated. For the most current method of generating SSL certificates for Tailscale, please follow the instructions in the <a href="https://sim642.eu/blog/2024/08/11/tailscale-https-certificate-on-synology-nas/">original article by sim642</a>.</blockquote><h3>Introduction</h3><p>In the world of networking, securing connections between devices is paramount. <a href="https://tailscale.com/">Tailscale</a>, a modern VPN solution, offers a secure way to connect your devices. For <a href="https://www.synology.com/en-global/dsm">Synology DSM</a> users, automating the configuration of Tailscale certificates can enhance security while simplifying the process. This article provides a comprehensive guide and a Bash script to automate the setup of Tailscale certificates on Synology DSM.</p><h3>Understanding Tailscale</h3><p>Tailscale is a Zero Trust network that creates a secure network between your computers, servers, and cloud instances. It’s built on top of <a href="https://www.wireguard.com/">WireGuard</a>, a state-of-the-art, high-performance VPN protocol. The main advantage of Tailscale is its simplicity in setup and use, combined with robust security features.</p><h3>Benefits of Tailscale</h3><ul><li>Ease of Use: Tailscale simplifies the network management process.</li><li>Secure: It encrypts your traffic, ensuring data security.</li><li>Scalable: Suitable for both small and large networks.</li></ul><h3>Setting Up Tailscale on Synology DSM</h3><p>Synology DSM is renowned for its robust and user-friendly NAS (Network-Attached Storage) operating system. Integrating Tailscale with DSM enhances your network’s security. The process involves enabling SSH, creating a script, and executing it.</p><h3>Pre-requisites</h3><ul><li>A Synology DSM device with Tailscale installed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*qlq1smLqMnnAGDbE2xo3hQ.png" /></figure><h3>Part 1: Enabling SSH on Synology DSM</h3><ol><li>Log into DSM: Access your DSM via a web browser and log in.</li><li>Open Control Panel: Navigate to the Control Panel.</li><li>Access Terminal &amp; SNMP: Locate the “Terminal &amp; SNMP” section.</li><li>Enable SSH: Check the “Enable SSH service” box, opting for the default port (22) or another as needed.</li><li>Apply Settings: Click “Apply” to enable SSH.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5uZLjRxJ07OdGhtbJxZRg.png" /></figure><h3>Part 2: Creating and Executing the Script</h3><ol><li>SSH into DSM: Use an SSH client to connect to your DSM using ssh [username]@[DSM IP address] -p [port].</li><li>Create Script File: Create a new file named tailscale_cert_script.sh using a text editor, such as vi</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*UCywKV6HmmVSHIvbahEfKA.png" /></figure><p>3. Script Content: Input the following script into the file:</p><pre>#!/bin/bash<br><br># Ensuring Root Privileges<br>if [ &quot;$EUID&quot; -ne 0 ]; then<br>  echo &quot;This script must be run with sudo.&quot;<br>  exit 1<br>fi<br><br># Defining Variables<br>USER_HOME=$(eval echo ~$SUDO_USER)<br>TEMPDIR=&quot;$USER_HOME/.tailscale_certs&quot;<br>TS_DNS=$(tailscale status --json | jq -r &#39;.Self.DNSName | .[:-1]&#39;)<br>SYNO_ID=$(cat /usr/syno/etc/certificate/_archive/DEFAULT)<br><br># Cleanup of Old Certificates<br>rm -f &quot;$TEMPDIR/$TS_DNS.crt&quot; &quot;$TEMPDIR/$TS_DNS.key&quot; &quot;$TEMPDIR/$TS_DNS.pem&quot;<br><br># Directory Creation for Certs<br>mkdir -p &quot;$TEMPDIR&quot;<br><br># Generating Tailscale Certificates<br>tailscale cert --cert-file &quot;$TEMPDIR/$TS_DNS.crt&quot; --key-file &quot;$TEMPDIR/$TS_DNS.key&quot; &quot;$TS_DNS&quot;<br><br># Key Conversion to PKCS#8 Format<br>openssl pkcs8 -topk8 -nocrypt -in &quot;$TEMPDIR/$TS_DNS.key&quot; -out &quot;$TEMPDIR/p8file.pem&quot;<br><br># Copying Certificates to Synology<br>cp &quot;$TEMPDIR/$TS_DNS.crt&quot; &quot;/usr/syno/etc/certificate/_archive/$SYNO_ID/cert.pem&quot;<br>cp &quot;$TEMPDIR/$TS_DNS.crt&quot; &quot;/usr/syno/etc/certificate/_archive/$SYNO_ID/fullchain.pem&quot;<br>cp &quot;$TEMPDIR/p8file.pem&quot; &quot;/usr/syno/etc/certificate/_archive/$SYNO_ID/privkey.pem&quot;<br><br># Storing Certificates in a Specific Location<br>mkdir -p /etc/ssl/tailscale<br>cp &quot;$TEMPDIR/$TS_DNS.crt&quot; &quot;$TEMPDIR/$TS_DNS.key&quot; /etc/ssl/tailscale/<br><br># Restarting Synology Web Server<br>/usr/syno/bin/synosystemctl restart nginx</pre><blockquote><strong><em>Detailed Breakdown</em></strong></blockquote><blockquote><em>- Root Check: Ensures the script runs with root privileges.</em></blockquote><blockquote><em>- Variables Setup: Creates necessary paths and retrieves Tailscale DNS name.</em></blockquote><blockquote><em>- Cleanup: Removes any existing certificates to avoid conflicts.</em></blockquote><blockquote><em>- Certificate Generation: Uses Tailscale’s own tool to generate certificates.</em></blockquote><blockquote><em>- Key Conversion: Converts the key to the PKCS#8 format for compatibility.</em></blockquote><blockquote><em>- Copying Certificates: Places the new certificates in the appropriate Synology directories.</em></blockquote><blockquote><em>- Restarting Services: Restarts the Synology web server to apply changes.</em></blockquote><p>4. Making Script Executable: Adjust the file’s permissions to make it executable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-lPz-uOA8NVXhrBC3iE3Og.png" /></figure><p>5. Running the Script: Execute the script with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*hFyXVansFq-ZNuQv2QdKBg.png" /></figure><p>The final result on the Security/Certificate tab should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcUitKmFTbg31b50lAtcBQ.png" /></figure><p>After these steps, I could visit my Synology home page and could verify that HTTPS work out of the box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*74XTYJuHWE9xT5GBkFwl3w.png" /></figure><h3>Conclusion</h3><p>This quick guide provides a step-by-step approach for integrating Tailscale with Synology DSM and automating certificate configuration through a Bash script.</p><p>I’d like to express my gratitude to the community involved in the GitHub discussion, specifically in <a href="https://github.com/tailscale/tailscale/issues/4674">Tailscale GitHub Issue #4674</a>. Their insights and discussions were the catalyst for the ideas presented in this script.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a3c3b79e010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Static Website Hosting on AWS with Terraform: A Step-by-Step Tutorial]]></title>
            <link>https://medium.com/@walid.karray/mastering-static-website-hosting-on-aws-with-terraform-a-step-by-step-tutorial-5401ccd2f4fb?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5401ccd2f4fb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 12:36:25 GMT</pubDate>
            <atom:updated>2023-11-30T07:42:33.906Z</atom:updated>
            <content:encoded><![CDATA[<p>The shift to cloud and serverless solutions has revolutionized modern infrastructure, empowering organizations with simplicity and efficiency. This article provides a comprehensive guide to deploying a static website on AWS using Terraform, covering essential services such as S3 for storage, CloudFront for content delivery, and Route 53 for domain management. Each step is explained in detail.</p><p>The article addresses common challenges and shares best practices, empowering readers to leverage AWS for their website deployment needs.</p><p>Your feedback and discussions are highly appreciated, as they enrich the experience for all readers.</p><h3>Architecture Diagram :</h3><figure><img alt="This architecture illustrates the flow of hosting a static website on AWS using Route 53, CloudFront, S3, Certificate Manager, and a CloudFront Function." src="https://cdn-images-1.medium.com/max/951/1*wchsGJl8QGZvA4vrKMB4sQ.png" /><figcaption>Hosting Static Website on AWS — Architecture</figcaption></figure><p>This architecture illustrates the flow of hosting a static website on AWS using Route 53, CloudFront, S3, Certificate Manager, and a CloudFront Function. Here’s how it works:</p><p><strong>Client: </strong>Represents the end user who wishes to access the website.<br>When the client attempts to access the website, the first step is a DNS Lookup.</p><p><strong>Route53:</strong> Amazon Route 53 is AWS’s Domain Name System (DNS) cloud service.<br>When the client requests the website, the first thing that happens is a DNS query. This query is resolved by Route 53 to point towards the appropriate CloudFront distribution.</p><p><strong>Certificate Manager (TLS Certificate): </strong>AWS Certificate Manager is responsible for provisioning, managing, and deploying public and private SSL/TLS certificates for use with AWS services.<br>The certificate ensures that the website connection remains encrypted and is indicated by “HTTPS” in the URL.<br>The CloudFront Distribution fetches the SSL certificate from the Certificate Manager to ensure an HTTPS-only communication with the client.</p><p><strong>CloudFront Distribution: </strong>Amazon CloudFront is a content delivery network (CDN) service.<br>Upon DNS resolution by Route 53, the client’s request hits CloudFront, which may either serve cached content (for speed) or request the original content from the S3 bucket if it’s not already cached.<br>Uses the SSL certificate to ensure HTTPS communication.</p><p><strong>CloudFront OAC + S3 Bucket Policy: </strong><a href="https://aws.amazon.com/fr/blogs/networking-and-content-delivery/amazon-cloudfront-introduces-origin-access-control-oac/">Origin Access Control (OAC)</a> is a security feature that restricts access to an S3 bucket to only authorized CloudFront distributions. It is a more flexible and secure way to secure S3 buckets with CloudFront than the <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html">legacy OAI method</a>.</p><p>When using OAC, you can ensure that your S3 buckets are only accessible to authorized CloudFront distributions, which helps to keep your data safe and secure.</p><p><strong>CloudFront Function: </strong>This function is specifically designed for HTTP redirects. Let’s suppose someone types https://www.yourdoamin.com into their browser. Instead of staying on the ‘www’ version, this function quickly redirected them to the root domain https://yourdoamin.com (HTTP status 301). This provides a consistent domain experience and recommended for SEO and user experience.</p><p><strong>Private S3 Bucket: </strong>Amazon S3 (Simple Storage Service) is where the website’s static assets (HTML, CSS, JS, images) are stored.<br>It’s designated as “private”, meaning direct public access is restricted. Only CloudFront, with its OAC, can fetch content from this bucket.</p><p><strong>Static Web Files: </strong>Represents the static content of the website, such as HTML, CSS, and JavaScript files.<br>These files can be pushed or uploaded to the private S3 bucket, from where they are served to the end-users through the CloudFront distribution.</p><p>In summary, this architecture provides a <strong>highly available</strong> and <strong>scalable</strong> way to serve a static website with low latency. Using Route 53, CloudFront, Certificate Manager, and S3 in tandem, the setup ensures high availability, reduced latency, and HTTPS security for a seamless user experience.</p><h3>Bringing the Architecture to Life !</h3><h4>Prerequisites</h4><ul><li>AWS account with full administrative rights</li><li>Terraform installed (Version 1.5 or higher recommended)</li><li>A foundational understanding of AWS services and Terraform basics.</li></ul><h4>Overview of the Directory structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgE9fCMsyvd6WKhd6WKLAw.png" /></figure><p>The project’s structure shown above, all Terraform files reside in the root level. The <strong>./dist</strong> folder contains all static website assets, including HTML, CSS, JavaScript, and images, with ‘index.html’ serving as the main access point for users.</p><h4>Declaring and Using Variables</h4><p>Let’s start by declaring our required variables to keep our configurations dynamic. For clarity, each variable is paired with a comment outlining its use</p><pre>variable &quot;aws_region&quot; {<br>  type        = string<br>  description = &quot;AWS Region&quot;<br>}<br><br>variable &quot;prefix&quot; {<br>  type        = string<br>  description = &quot;The prefix to be added to resource names&quot;<br>}<br>variable &quot;domain_name&quot; {<br>  type        = string<br>  description = &quot;The domain name for the website.&quot;<br>}<br>variable &quot;bucket_name&quot; {<br>  type        = string<br>  description = &quot;The name of the bucket without the www. prefix. Normally domain_name.&quot;<br>}<br>variable &quot;common_tags&quot; {<br>  type        = map(string)<br>  description = &quot;Common tags you want applied to all components.&quot;<br>}</pre><h4>Defining Local Variables</h4><p>Local variables in Terraform allow for intermediate computations and transformations within a module, ensuring cleaner code without modifying the primary input variables.</p><p>locals.tf:</p><pre>locals {<br>  dist_dir    = &quot;${path.module}/dist&quot;<br>  module_name = basename(abspath(path.module))<br>  prefix      = var.prefix<br><br>  content_types = {<br>    &quot;.html&quot; : &quot;text/html&quot;,<br>    &quot;.css&quot; : &quot;text/css&quot;,<br>    &quot;.js&quot; : &quot;application/javascript&quot;,<br>    &quot;.json&quot; : &quot;application/json&quot;,<br>    &quot;.xml&quot; : &quot;application/xml&quot;,<br>    &quot;.jpg&quot; : &quot;image/jpeg&quot;,<br>    &quot;.jpeg&quot; : &quot;image/jpeg&quot;,<br>    &quot;.png&quot; : &quot;image/png&quot;,<br>    &quot;.gif&quot; : &quot;image/gif&quot;,<br>    &quot;.svg&quot; : &quot;image/svg+xml&quot;,<br>    &quot;.webp&quot; : &quot;image/webp&quot;,<br>    &quot;.ico&quot; : &quot;image/x-icon&quot;,<br>    &quot;.woff&quot; : &quot;font/woff&quot;,<br>    &quot;.woff2&quot; : &quot;font/woff2&quot;,<br>    &quot;.ttf&quot; : &quot;font/ttf&quot;,<br>    &quot;.eot&quot; : &quot;application/vnd.ms-fontobject&quot;,<br>    &quot;.otf&quot; : &quot;font/otf&quot;<br>  }<br>}</pre><p>In the code block above, the <strong>`dist_dir`</strong> directs to the static website files’ location, while `<strong>module_name</strong>` and `<strong>prefix</strong>` assist in resource organization. Additionally, the `<strong>content_types</strong>` map aligns file extensions with their appropriate MIME types, guaranteeing accurate content delivery for various assets.</p><h4>Setting up the AWS Provider</h4><p>Terraform providers are initial configurations that specify the cloud platform we’re using (e.g., AWS, Azure, GCP …). They enable Terraform to communicate with the cloud’s API. For our setup, we use two providers: one for general AWS services and a secondary one for ACM, which is required for CloudFront.</p><p>provider.tf:</p><pre>provider &quot;aws&quot; {<br>  region                   = var.aws_region<br>}<br><br># CloudFront requires SSL certificates to be provisioned in the North Virginia (us-east-1) region.<br>provider &quot;aws&quot; {<br>  alias  = &quot;acm_provider&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><h4>Create an S3 Bucket for Your Website</h4><p>We will use an Amazon S3 bucket to host the static assets of our website</p><p>aws_s3_bucket.tf:</p><pre># S3 src website bucket<br>resource &quot;aws_s3_bucket&quot; &quot;static_website&quot; {<br>  bucket = var.bucket_name<br><br>  tags = var.common_tags<br>}<br><br>resource &quot;aws_s3_bucket_website_configuration&quot; &quot;website_bucket&quot; {<br>  bucket = aws_s3_bucket.static_website.id<br><br>  index_document {<br>    suffix = &quot;index.html&quot;<br>  }<br><br>  error_document {<br>    key = &quot;index.html&quot;<br>  }<br><br>}<br><br># S3 bucket ACL access<br><br>resource &quot;aws_s3_bucket_ownership_controls&quot; &quot;website_bucket&quot; {<br>  bucket = aws_s3_bucket.static_website.id<br>  rule {<br>    object_ownership = &quot;BucketOwnerPreferred&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;website_bucket&quot; {<br>  bucket = aws_s3_bucket.static_website.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br><br>}<br><br>resource &quot;aws_s3_bucket_acl&quot; &quot;website_bucket&quot; {<br>  depends_on = [<br>    aws_s3_bucket_ownership_controls.website_bucket,<br>    aws_s3_bucket_public_access_block.website_bucket,<br>  ]<br><br>  bucket = aws_s3_bucket.static_website.id<br>  acl    = &quot;private&quot;<br>}<br><br></pre><p>Let’s break down the role of each Terraform resource.</p><p><strong><em>S3 Bucket Creation</em> </strong>(aws_s3_bucket): This resource defines the primary storage location, named after var.bucket_name, for our website&#39;s static content like HTML, CSS, and JavaScript files.</p><p><strong><em>Website Configuration</em></strong><em> </em>(aws_s3_bucket_website_configuration): This configuration sets up the S3 bucket to behave like a web server. When someone accesses the root of our domain, they’re served the index.html file. If there&#39;s an error, we redirect them back to the main page.</p><p><strong><em>Bucket Ownership Controls</em></strong><em> </em>(aws_s3_bucket_ownership_controls): This establishes that the default owner of objects uploaded to our bucket, unless specified otherwise, will be the bucket owner.</p><p><strong><em>Public Access Restrictions</em></strong> (aws_s3_bucket_public_access_block): For security, this configuration ensures that our bucket is not publicly accessible. It blocks public ACLs, policies, and restricts public access to ensure our content remains private.</p><p><strong><em>Bucket Access Control List (ACL)</em></strong><em> </em>(aws_s3_bucket_acl): This resource, which depends on the aforementioned ownership and public access controls, confirms that the overall access level for the bucket is set to “private”, reinforcing our data security.</p><h4>Define SSL Certificate</h4><p>For a secure website, we need an SSL certificate. Let’s set one up using AWS Certificate Manager.</p><p>aws_acm_certificate.tf:</p><pre># SSL Certificate<br>resource &quot;aws_acm_certificate&quot; &quot;ssl_certificate&quot; {<br>  provider                  = aws.acm_provider<br>  domain_name               = var.domain_name<br>  subject_alternative_names = [&quot;*.${var.domain_name}&quot;]<br>  #validation_method         = &quot;EMAIL&quot;<br>  validation_method = &quot;DNS&quot;<br><br>  tags = var.common_tags<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br># Uncomment the validation_record_fqdns line if you do DNS validation instead of Email.<br>resource &quot;aws_acm_certificate_validation&quot; &quot;cert_validation&quot; {<br>  provider                = aws.acm_provider<br>  certificate_arn         = aws_acm_certificate.ssl_certificate.arn<br>  validation_record_fqdns = [for record in aws_route53_record.cert_validation : record.fqdn]<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;cert_validation&quot; {<br>  for_each = {<br>    for dvo in aws_acm_certificate.ssl_certificate.domain_validation_options : dvo.domain_name =&gt; {<br>      name   = dvo.resource_record_name<br>      record = dvo.resource_record_value<br>      type   = dvo.resource_record_type<br>    }<br>  }<br>  allow_overwrite = true<br>  name            = each.value.name<br>  records         = [each.value.record]<br>  ttl             = 60<br>  type            = each.value.type<br>  zone_id         = aws_route53_zone.main.zone_id<br>}</pre><p>Here’s a breakdown of aws_acm_certificate.tf:</p><ul><li>aws_acm_certificate: This resource provisions an SSL certificate for our domain. It uses the DNS validation method, making the process seamless and not reliant on email confirmations.</li><li>aws_acm_certificate_validation: Post the certificate creation, this resource ensures its validation. If you prefer DNS validation over email, ensure the validation_record_fqdns line is uncommented.</li></ul><blockquote>Note to Remember: DNS validation can take some time. It’s dependent on DNS propagation, so you might need to wait a while before the validation completes</blockquote><ul><li>aws_route53_record: The SSL certificate necessitates specific DNS records for its validation. This resource creates those records in AWS Route 53. Later on, we will delve deeper into Route 53 configurations to integrate it thoroughly with our website setup.</li></ul><h4>Configure CloudFront Distribution</h4><p>For any online business, delivering content swiftly and securely is key. AWS CloudFront addresses this by spreading content through a worldwide network of data centers, guaranteeing quicker load times and bolstered security. <br>Additionally, CloudFront is not just about speed and security. It offers a suite of advanced features, like edge computing capabilities, content optimization, and detailed analytics, making it a comprehensive solution for content delivery needs.</p><p>aws_cloudfront_distribution.tf:</p><pre>resource &quot;aws_cloudfront_origin_access_control&quot; &quot;current&quot; {<br>  name                              = &quot;OAC ${aws_s3_bucket.static_website.bucket}&quot;<br>  origin_access_control_origin_type = &quot;s3&quot;<br>  signing_behavior                  = &quot;always&quot;<br>  signing_protocol                  = &quot;sigv4&quot;<br>}<br><br>resource &quot;aws_cloudfront_distribution&quot; &quot;s3_distribution&quot; {<br>  depends_on = [aws_s3_bucket.static_website]<br>  origin {<br>    domain_name              = aws_s3_bucket.static_website.bucket_regional_domain_name<br>    origin_id                = &quot;${var.bucket_name}-origin&quot;<br>    origin_access_control_id = aws_cloudfront_origin_access_control.current.id<br>  }<br>  comment         = &quot;${var.domain_name} distribution&quot;<br>  enabled         = true<br>  is_ipv6_enabled = true<br>  http_version    = &quot;http2and3&quot;<br>  price_class     = &quot;PriceClass_100&quot; // Use only North America and Europe<br>  // wait_for_deployment = true<br>  aliases = [<br>    var.domain_name,<br>    &quot;www.${var.domain_name}&quot;<br>  ]<br>  default_root_object = &quot;index.html&quot;<br><br>  default_cache_behavior {<br>    cache_policy_id        = &quot;658327ea-f89d-4fab-a63d-7e88639e58f6&quot;<br>    viewer_protocol_policy = &quot;redirect-to-https&quot;<br>    allowed_methods        = [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>    cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    compress               = true<br>    target_origin_id       = &quot;${var.bucket_name}-origin&quot;<br><br> <strong>   //TODO : function_association</strong><br><br>  }<br>  restrictions {<br>    geo_restriction {<br>      restriction_type = &quot;none&quot;<br>      locations        = []<br>    }<br>  }<br>  viewer_certificate {<br>    acm_certificate_arn      = aws_acm_certificate_validation.cert_validation.certificate_arn<br>    ssl_support_method       = &quot;sni-only&quot;<br>    minimum_protocol_version = &quot;TLSv1.2_2021&quot;<br>  }<br>  tags = var.common_tags<br>}<br><strong>//TODO : aws_cloudfront_function for www redirect</strong></pre><p>Diving into the Terraform code above:</p><p>The aws_cloudfront_origin_access_control Terraform resource creates an AWS CloudFront Origin Access Control (OAC), which is a secure way to grant CloudFront access to your S3 bucket.</p><p>OAC use AWS Identity and Access Management (IAM) role trusts to provide CloudFront with short-term credentials to access your S3 bucket. This is more secure than using a CloudFront Origin Access Identity (OAI), which is a deprecated resource that provided CloudFront with long-term credentials.</p><p>aws_cloudfront_distribution: The primary configuration for our content delivery. Let&#39;s break this down:</p><ul><li>origin: Defines the origin of our content - in this case, our S3 bucket.</li><li>default_cache_behavior: Sets the caching policies, HTTP methods, and ensures our content is delivered via HTTPS for enhanced security. Here, the function_association also triggers our URL redirection function whenever a user request is made.</li><li>aliases: Configures the domain names associated with the CloudFront distribution, facilitating access via our custom domain.</li><li>restrictions: Geo-restrictions can be defined, but here it&#39;s set to &#39;none&#39;, allowing global access.</li><li>viewer_certificate: Associates our SSL certificate with the distribution, enabling HTTPS access.</li></ul><h4>Implementing CloudFront Function for URL Redirection</h4><p>When users visit our site with ‘www’ (like https://www.yourdoamin.com), we want them to be sent straight to the root domain https://yourdoamin.com. This gives our website address a uniform look and can help with our search ranking (SEO). That’s where CloudFront functions come in.</p><p><strong><em>Why Choose CloudFront Functions Over Lambda@Edge?</em></strong></p><ol><li><strong>Simplicity:</strong> CloudFront Functions are specialized for lighter, high-frequency tasks like URL redirections, making them straightforward to use.</li><li><strong>Low Latency: </strong>Designed for near-instantaneous execution, they ensure rapid, barely noticeable redirections for users.</li><li><strong>Cost-Effective:</strong> Typically more economical than Lambda@Edge, especially for high-request use cases like URL redirects.</li><li><strong>Ease of Deployment:</strong> Simpler and more direct management and deployment compared to Lambda@Edge.</li></ol><p>cloudfront-function.js:</p><pre>function handler(event) {<br>    var request = event.request;<br>    var hostHeader = request.headers.host.value;<br><br>    // Regular expression to extract the top-level domain and root domain<br>    var domainRegex = /(?:.*\.)?([a-z0-9\-]+\.[a-z]+)$/i;<br>    var match = hostHeader.match(domainRegex);<br><br>    // If the regex does not match, or the host does not start with &#39;www.&#39;, return the original request<br>    if (!match || !hostHeader.startsWith(&#39;www.&#39;)) {<br>        return request;<br>    }<br><br>    // Extract the root domain<br>    var rootDomain = match[1];<br><br>    // Construct and return the redirect response<br>    return {<br>        statusCode: 301,<br>        statusDescription: &#39;Moved Permanently&#39;,<br>        headers: {<br>            &quot;location&quot;: { &quot;value&quot;: &quot;https://&quot; + rootDomain + request.uri },<br>            &quot;cache-control&quot;: { &quot;value&quot;: &quot;max-age=3600&quot; }<br>        }<br>    };<br>}</pre><p>To integrate this function code to our CloudFront distribution, we’ll make two updates in the aws_cloudfront_distribution.tf file:</p><pre>//  *** Other configurations and code are hidden for clarity. ***<br><br>resource &quot;aws_cloudfront_distribution&quot; &quot;s3_distribution&quot; {<br><br>    //  *** Other configurations and code are hidden for clarity. ***<br><br>    default_cache_behavior {<br>        cache_policy_id        = &quot;658327ea-f89d-4fab-a63d-7e88639e58f6&quot;<br>        viewer_protocol_policy = &quot;redirect-to-https&quot;<br>        allowed_methods        = [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>        cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;]<br>        compress               = true<br>        target_origin_id       = &quot;${var.bucket_name}-origin&quot;<br>    <br>   <strong>     function_association {<br>          event_type   = &quot;viewer-request&quot;<br>          function_arn = aws_cloudfront_function.www_redirect.arn<br>        }</strong><br>      }<br><br>   //  *** Other configurations and code are hidden for clarity. ***<br><br>}<br><br>/*<br>  A CloudFront function to redirect www-prefixed URLs to the apex domain,<br>  enhancing user experience and consolidating domain authority.<br>*/<strong><br>resource &quot;aws_cloudfront_function&quot; &quot;www_redirect&quot; {<br>  name    = &quot;${local.prefix}-www-redirect&quot;<br>  runtime = &quot;cloudfront-js-1.0&quot;<br>  code    = file(&quot;./cloudfront-function.js&quot;)<br>  publish = true<br>}</strong></pre><p><strong>1) aws_cloudfront_function</strong>: This is the core terraform definition of our redirection function. It specifies:</p><ul><li><strong>name:</strong> A unique identifier for the function.</li><li><strong>runtime:</strong> The runtime environment CloudFront uses to execute the function. (cloudfront-js-1.0).</li><li><strong>code: </strong>Points to the actual JavaScript code for the function, which resides in the file cloudfront-function.js.</li><li><strong>publish:</strong> When set to true, it means the function is immediately published and ready for association with distributions.</li></ul><p><strong>2) function_association</strong> within <strong>default_cache_behavior</strong>: This piece of configuration associates our function with the CloudFront distribution. Whenever a viewer request event occurs, the function specified by its ARN is triggered.</p><h4>Configure Domain with Route53</h4><p>Amazon Route53’s `Hosted Zone` is a container that holds information about how you want to route traffic for a specific domain, like `example.com`. It encompasses domain-specific record sets, guiding traffic to the intended destinations. When you register or manage a domain in Route53, you’re essentially creating or editing a hosted zone for it.</p><p>In this section we will setup out website’s domain using Route53 zone.</p><p>aws_route53_record.tf:</p><pre>resource &quot;aws_route53_zone&quot; &quot;main&quot; {<br>  name = var.domain_name<br>  tags = var.common_tags<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;root_a&quot; {<br>  zone_id = aws_route53_zone.main.zone_id<br>  name    = var.domain_name<br>  type    = &quot;A&quot;<br><br>  alias {<br>    name                   = aws_cloudfront_distribution.s3_distribution.domain_name<br>    zone_id                = aws_cloudfront_distribution.s3_distribution.hosted_zone_id<br>    evaluate_target_health = false<br>  }<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;www_a&quot; {<br>  zone_id = aws_route53_zone.main.zone_id<br>  name    = &quot;www.${var.domain_name}&quot;<br>  type    = &quot;A&quot;<br><br>  alias {<br>    name                   = aws_cloudfront_distribution.s3_distribution.domain_name<br>    zone_id                = aws_cloudfront_distribution.s3_distribution.hosted_zone_id<br>    evaluate_target_health = false<br>  }<br>}</pre><p>Examining each Terraform resource :</p><ul><li><strong>aws_route53_zone “main”:</strong> This resource represents a hosted zone for your domain on Route53. It essentially provides a space to define how you want to route traffic for the domain. The name attribute specifies the domain name, and we attach any relevant tags for organizational purposes.</li><li><strong>aws_route53_record “root_a”: </strong>Here, we’re defining an ‘A’ record, which is essential for translating domain names into IP addresses. This record points our root domain (like example.com) to our CloudFront distribution. We utilize the alias block to directly associate this domain with the CloudFront distribution, ensuring that when users access our domain, they&#39;re served content from our CloudFront distribution.</li><li><strong>aws_route53_record “www_a”</strong>: Similarly, this ‘A’ record is designed for the ‘www’ version of our domain (like www.example.com). It ensures that whether users enter the root domain or the &#39;www&#39; version, they&#39;re redirected to the same CloudFront distribution. Again, the alias block is used to link this to the CloudFront distribution.</li></ul><h4>Secure Your S3 Bucket</h4><p>When hosting content on an S3 bucket, ensure proper access control. The aws_s3_bucket_policy &quot;allow_cloudfront&quot; grants CloudFront read-only access via Origin Access Control (OAC). This approach ensures exclusive content access through CloudFront.</p><p>aws_s3_bucket_policy.tf:</p><pre>resource &quot;aws_s3_bucket_policy&quot; &quot;allow_cloudfront&quot; {<br>  bucket = aws_s3_bucket.static_website.id<br>  policy = data.aws_iam_policy_document.cloudfront.json<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;cloudfront&quot; {<br>  statement {<br>    sid     = &quot;AllowCloudFrontServicePrincipalReadOnly&quot;<br>    effect  = &quot;Allow&quot;<br>    actions = [&quot;s3:GetObject&quot;]<br>    resources = [<br>      aws_s3_bucket.static_website.arn,<br>      &quot;${aws_s3_bucket.static_website.arn}/*&quot;<br>    ]<br><br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;cloudfront.amazonaws.com&quot;]<br>    }<br><br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;AWS:SourceArn&quot;<br>      values = [<br>        aws_cloudfront_distribution.s3_distribution.arn<br>      ]<br>    }<br>  }<br>}</pre><h4>Automatically upload your website files to S3 when you deploy</h4><p>When deploying your static website, it’s essential to ensure that your site’s files are correctly and efficiently transferred to the S3 bucket. The terraform file below provides an automated approach to achieve this.</p><p>aws_s3_object.tf:</p><pre># Uploads all files from the local &quot;src/dist&quot; directory to a specified AWS S3 bucket.<br>resource &quot;aws_s3_object&quot; &quot;static_file&quot; {<br>  for_each     = fileset(local.dist_dir, &quot;**&quot;)<br>  bucket       = aws_s3_bucket.static_website.id<br>  key          = each.key<br>  source       = &quot;${local.dist_dir}/${each.value}&quot;<br>  content_type = lookup(local.content_types, regex(&quot;\\.[^.]+$&quot;, each.value), null)<br>  etag         = filemd5(&quot;${local.dist_dir}/${each.value}&quot;)<br>}</pre><p>Within the aws_s3_object resource, each file from the local &quot;./<strong>dist</strong>&quot; directory is iterated over and uploaded to the specified AWS S3 bucket. The for_each directive here is used to go through each file in the directory. This means, when you run the deployment process, Terraform will automatically handle the upload of every file, ensuring the structure of your website remains consistent in the cloud. Furthermore, by determining the content_type dynamically, the configuration ensures proper handling and delivery of different file types, enhancing the performance and user experience of your site.</p><h4>Outputs</h4><p>Terraform outputs are essential for getting important information about generated resources, such as S3 bucket names and CloudFront URLs, for validation and post-deployment access.</p><p>outputs.tf:</p><pre>output &quot;dist_files&quot; {<br>  value = fileset(local.dist_dir, &quot;**/*&quot;)<br>}<br><br>output &quot;s3_website_endpoint&quot; {<br>  description = &quot;S3 hosting URL (HTTP)&quot;<br>  value       = &quot;http://${aws_s3_bucket_website_configuration.website_bucket.website_endpoint}&quot;<br>}<br><br>output &quot;cloudfront_id&quot; {<br>  description = &quot;Cloudfront ID&quot;<br>  value       = aws_cloudfront_distribution.s3_distribution.id<br>}<br><br>output &quot;cloudfront_url&quot; {<br>  description = &quot;Cloudfront distribution URL (HTTPS)&quot;<br>  value       = &quot;https://${aws_cloudfront_distribution.s3_distribution.domain_name}&quot;<br>}<br><br>output &quot;website_url&quot; {<br>  description = &quot;Website URL (HTTPS)&quot;<br>  value       = &quot;https://${var.domain_name}&quot;<br>}</pre><h4>Terraform Remote State (S3 &amp; Dynamodb Backend)</h4><p><em>This section is optional, but recommended for maintaining best practice standards.</em></p><p>Managing Terraform remote state is essential for teamwork and secure, scalable infrastructure. Using a remote state backend ensures that everyone on your team is working with the same infrastructure, and it helps you make changes safely.</p><p>To do so, we need to create a Terraform configuration file called</p><p>backend.tf :</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    encrypt        = true<br>    bucket         = &quot;my-org-tf-state&quot;<br>    dynamodb_table = &quot;my-org-tf-state-lock&quot;<br>    key            = &quot;my-static-website.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>  }<br>}</pre><p>The provided Terraform code defines how to handle the state of your infrastructure using AWS S3 as a backend. In the context of Terraform, a backend determines how the state is loaded and how an operation such as apply is executed. It abstracts state management and locks the state to prevent conflicts in a team environment.</p><p>In the given code:</p><ul><li>backend &quot;s3&quot; specifies AWS S3 to store the state file.</li><li>encrypt = true ensures your state file is encrypted.</li><li>bucket = &quot;my-org-tf-state&quot; names your S3 bucket.</li><li>dynamodb_table = &quot;my-org-tf-state-lock&quot; uses DynamoDB for state locking.</li><li>key = &quot;my-static-website.tfstate&quot; sets the state file name.</li><li>region = &quot;us-east-1&quot; sets AWS region where everything is stored. Change the region to where you prefer to store your state file, considering latency and any data residency requirements.</li></ul><blockquote><strong>Important Notes for Adaptation:</strong></blockquote><blockquote><strong>Bucket Name:</strong> Ensure <em>bucket</em> is unique across all AWS since S3 bucket names are globally unique. Replace &quot;my-org&quot; with your organization or project’s name.</blockquote><blockquote><strong>Region: </strong>Change the <em>region</em> to where you prefer to store your state file, considering latency and any data residency requirements.</blockquote><p>Discover further details on provisioning the necessary resources for S3 remote state management by visiting the following the <a href="https://developer.hashicorp.com/terraform/language/settings/backends/s3">HashiCorp Developer Guide</a>.</p><h4>Assigning Variable Values</h4><p>Early in this article, we defined various variables in our variables.tf file to create a flexible and reusable Terraform configuration. Now, it&#39;s time to assign specific values to these predefined variables using the terraform.tfvars file. This practice aids in keeping our configurations modular and secure, preventing sensitive data from being inadvertently exposed in our main configuration files.</p><p>Here’s a quick snapshot of what your terraform.tfvars might look like:</p><pre>aws_region  = &quot;eu-west-1&quot;<br>prefix      = &quot;static-website&quot;<br>domain_name = &quot;example.com&quot;<br>bucket_name = &quot;my-static-site-frontend&quot;<br><br>common_tags = {<br>  ManagedBy = &quot;Terraform&quot;<br>  Project   = &quot;Static Website&quot;<br>}</pre><p>You will need to change the following values:</p><ul><li>Replace the domain_name value with your own domain name, which must already be registered with Route 53 or another domain registrar.</li><li>You will need to replace bucket_name value with a unique bucket name for your static website.</li></ul><h4>To the Cloud ! 🚀 Deploy Your Website to AWS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*PzAHRRTg18oGUBE4" /></figure><p>Execute the following commands in a terminal from your project directory</p><p>[terraform init]Prepares your Terraform project for use by installing necessary plugins and setting up the backend for state management. It’s the first command to run in a new Terraform project to get it ready for further actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVh9GC6mdXsncuGwP8anpg.png" /></figure><p>Console output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*LGam9jQa0tbYnPvxtsl4Cw.png" /></figure><p><strong>2. Apply Configuration</strong></p><p>[terraform apply] command configures your AWS resources to match your code specifications. It provides a preview of changes, seeks your approval, and subsequently adjusts AWS resources, handling creation, modification, or deletion as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGbtgHs26uC4eKJ50ttpgQ.png" /></figure><p>Console output:</p><p>You should type “yes” in order to apply changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*qUZvJFkas53kLkyL7fn-7w.png" /></figure><blockquote>Please note that deploying might take a while, potentially up to 30 minutes, due to CloudFront’s propagation across its extensive global server network and the necessary time for SSL certificate validation.</blockquote><p>Once Terraform has finished deploying your infrastructure, you will see a success message with the output variables printed, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*eyIMqe76a5lp4X4CArkhvQ.png" /></figure><h3>Confirming successful website deployment</h3><p>Now, let’s see our website in action!</p><p>Launch your browser and navigate to your domain using HTTPS, like so: <a href="https://www.yourdoamin.com./">https://www.yourdoamin.com</a> .</p><p>Your page should now load as shown in the screenshot below. If it doesn’t, or if you encounter any issues, please refer to the <strong>Troubleshooting</strong> section that follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDZ2wbdZp92ahRajzEZ63g.png" /></figure><p>Next, let’s verify that the redirection from “www” to the root domain is functioning. Type https://www.yourdoamin.com into your browser - it should seamlessly redirect you to https://yourdomain.com. This redirection is made possible thanks to the configured CloudFront functions, ensuring both better SEO and consistent user experience.</p><h3>Troubleshooting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*QuA_nGsGZgjkjjJg.png" /></figure><p>If you’re experiencing issues with DNS propagation, it could stem from a misconfiguration of your domain name’s name servers, especially if your domain is registered with a registrar different from Route53. In such cases, ensure to replace the name servers of your domain name with the NS records found in your Route53 Hosted Zone. This aligns your domain with AWS and assists in resolving any propagation issues that may arise.</p><p>After adjusting your name servers, it can be handy to verify that the changes are propagating across the internet. A quick way to do this is by using an online DNS checker tool. You can visit <a href="https://www.dnschecker.org/">DNS Checker</a> to view the status of your domain’s DNS propagation worldwide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXKlbke59pfxAnu32DAztA.png" /></figure><h3>Estimating Your AWS Bill !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*t6EYx8Ib8P4d45Kq" /></figure><p>Let’s take a look at the possible expenses for hosting a static website on AWS, considering our current structure. Assuming each page load retrieves 1MB of data, and our website takes up 8MB of space on S3, and expecting about 1000 daily visitors, we’ll approximate the costs, keeping in mind the AWS pricing as of October 2023.</p><p><strong>1. S3 Bucket</strong></p><ul><li>Storing Your Website: Hosting 8MB of data on S3 will cost just a few cents per month because AWS charges <strong>$0.023</strong> per GB.</li><li>Loading Your Website: If every visitor causes 10 GET requests (300,000 in a month), the charge would be around <strong>$0.12</strong> monthly.</li></ul><p><strong>2. Amazon CloudFront</strong></p><ul><li>Sending Data to Visitors: If each visitor downloads 1MB of data, that’s 30GB per month. In the USA, the cost would be around <strong>$2.55 </strong>each month.</li><li>Handling Requests: If each visitor causes 10 HTTP requests (300,000 in a month), it’ll cost about <strong>$0.30</strong> monthly.</li></ul><p><strong>3. AWS Certificate Manager</strong></p><ul><li>SSL/TLS Certificates: <strong>No extra cost</strong> here! ACM provides these certificates for free with CloudFront.</li></ul><p><strong>4. Route 53</strong></p><ul><li>Hosted Zone: One hosted zone equates to <strong>$0.50</strong> monthly.</li><li>Handling Queries: For our 300,000 queries, the monthly cost would be about <strong>$0.12</strong>.</li></ul><p><strong>5. CloudFront Functions</strong></p><ul><li>Running Functions: With 30,000 runs per month, the charge is just a few cents because AWS charges <strong>$0.1</strong> per million runs.</li></ul><p>Total Monthly Cost Estimate: Around<strong> $3.57</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*KU_LvmQ-uSsH_l72" /></figure><p>These numbers provide a rough idea and the actual cost may vary a bit based on exact usage and any price changes from AWS. For a more detailed estimate tailored to your unique usage, try using the <a href="https://calculator.aws/">AWS Pricing Calculator</a>. And remember, it’s smart to keep an eye on your AWS costs and usage with tools like AWS Budgets and Cost Explorer.</p><h3>Summary</h3><p>In this article, we have shown you how to create a secure and scalable static website infrastructure on AWS using Terraform.</p><p>We covered the following steps:</p><ul><li>Setting up the AWS provider</li><li>Creating an S3 bucket for website content</li><li>Securing traffic with an SSL certificate through ACM</li><li>Speeding up content delivery with CloudFront</li><li>We used CloudFront Origin Access Control (OAC) to restrict access to the S3 bucket to only authorized CloudFront distributions. This helps to keep data safe and secure.</li><li>Ensuring a consistent domain experience with a URL redirection function</li></ul><p>As your team grows and your projects expand, you can use Terraform workspaces to manage multiple instances of infrastructure in an isolated and organized manner. This is perfect for development, staging, and production environments.</p><p>Thank you for reading this article. For a deeper dive and a more hands-on experience, check out the full project on GitHub repository link: <a href="https://github.com/tux86/static-website-hosting-amazon-s3">https://github.com/tux86/static-website-hosting-amazon-s3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5401ccd2f4fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Todo App with TypeScript Using Clean Architecture: A Detailed Look at the Directory…]]></title>
            <link>https://medium.com/@walid.karray/building-a-todo-app-with-typescript-using-clean-hexagonal-architecture-a-detailed-look-at-the-d9e177f9f31?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e177f9f31</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 09:14:08 GMT</pubDate>
            <atom:updated>2023-04-19T13:03:33.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gebito6t2hpTkIuv" /><figcaption>Photo by <a href="https://unsplash.com/de/@dotnny?utm_source=medium&amp;utm_medium=referral">Donny Jiang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building a Todo App with TypeScript Using Clean Architecture: A Detailed Look at the Directory Structure</h3><h3>Introduction</h3><p>Clean Architecture, also known as Hexagonal Architecture, is a design pattern that promotes a modular approach to software development by emphasizing the separation of concerns, maintainability, and testability. This pattern allows developers to build scalable and adaptable applications, with each component being independent and easily replaceable. In this article, we’ll take an in-depth look at the directory structure and its contents when creating a Todo app using TypeScript and Clean Architecture principles. We will explore each directory, explain its purpose, and delve into the specific files inside it, providing a comprehensive understanding of how the various components work together to create a cohesive application.</p><h3>Directory Structure</h3><p>Here’s the proposed directory structure for a TypeScript Todo app using Clean Architecture:</p><pre>todo-app/<br>│<br>├── src/                           # Contains the source code of the app<br>│   ├── core/                      # Contains the core business logic of the app<br>│   │   ├── domain/                # Contains the domain entities and business rules<br>│   │   │   ├── entities/          # Contains the Todo entity and related classes<br>│   │   │   │   ├── todo.ts<br>│   │   │   │   └── ...<br>│   │   │   └── use-cases/         # Contains the business use cases (application services)<br>│   │   │       ├── createTodo.ts<br>│   │   │       ├── deleteTodo.ts<br>│   │   │       ├── updateTodo.ts<br>│   │   │       └── ...<br>│   │   └── repositories/          # Contains repository interfaces for data access<br>│   │       ├── todoRepository.ts<br>│   │       └── ...<br>│   │<br>│   ├── infrastructure/            # Contains the implementation of external dependencies<br>│   │   ├── database/              # Contains the database setup and ORM configuration<br>│   │   │   ├── connection.ts<br>│   │   │   └── ...<br>│   │   └── repositories/          # Contains the implementation of repository interfaces<br>│   │       ├── todoRepositoryImpl.ts<br>│   │       └── ...<br>│   │<br>│   ├── application/               # Contains the application layer logic<br>│   │   ├── controllers/           # Contains the API controllers (e.g., for RESTful APIs)<br>│   │   │   ├── todoController.ts<br>│   │   │   └── ...<br>│   │   └── dtos/                  # Contains data transfer objects for input validation and output formatting<br>│   │       ├── createTodoDTO.ts<br>│   │       ├── updateTodoDTO.ts<br>│   │       └── ...<br>│   │<br>│   └── config/                    # Contains configuration files and constants<br>│       ├── app.ts                 # Main application configuration<br>│       ├── database.ts            # Database configuration<br>│       └── ...<br>│<br>├── tests/                         # Contains unit and integration tests<br>│   ├── core/<br>│   │   ├── domain/<br>│   │   │   └── ...<br>│   │   └── repositories/<br>│   │       └── ...<br>│   ├── infrastructure/<br>│   │   └── ...<br>│   └── application/<br>│       ├── controllers/<br>│       │   └── ...<br>│       └── ...<br>│<br>├── .gitignore<br>├── package.json<br>├── tsconfig.json<br>└── README.md</pre><p><strong>Core Layer</strong></p><p>The core layer contains the main business logic of the application. It is composed of three main subdirectories:</p><ul><li>domain: This directory contains the domain entities and business rules. For our Todo app, we will have a Todo entity and various use cases, such as creating, updating, and deleting todos.</li><li>entities: This directory holds the Todo entity (todo.ts) and any related classes. The todo.ts file defines the structure and behavior of a Todo item.</li></ul><p>Here&#39;s a snippet of the todo.ts file:</p><pre>class Todo {<br>  id: string;<br>  title: string;<br>  description: string;<br>  completed: boolean;<br>  createdAt: Date;<br>  updatedAt: Date;<br><br>  constructor(title: string, description: string) {<br>    this.id = generateId();<br>    this.title = title;<br>    this.description = description;<br>    this.completed = false;<br>    this.createdAt = new Date();<br>    this.updatedAt = new Date();<br>  }<br><br>  markAsCompleted(): void {<br>    this.completed = true;<br>    this.updatedAt = new Date();<br>  }<br><br>  // Additional methods for updating, etc.<br>}<br><br>function generateId(): string {<br>  // Generate a unique identifier for each Todo instance<br>}</pre><p>In this snippet, the Todo class represents a single Todo item, with properties such as id, title, description, completed, createdAt, and updatedAt. The class also includes methods for managing the Todo item, such as markAsCompleted().</p><ul><li>use-cases: This directory contains the business use cases (application services) for the Todo app, such as createTodo.ts, deleteTodo.ts, and updateTodo.ts. These files define the core business logic for managing Todo items.</li></ul><p>For example, here’s a snippet of the createTodo.ts file:</p><pre>import { Todo } from &#39;../entities/todo&#39;;<br>import { TodoRepository } from &#39;../repositories/todoRepository&#39;;<br><br>interface CreateTodoInput {<br>  title: string;<br>  description: string;<br>}<br><br>export class CreateTodo {<br>  private todoRepository: TodoRepository;<br><br>  constructor(todoRepository: TodoRepository) {<br>    this.todoRepository = todoRepository;<br>  }<br><br>  async execute(input: CreateTodoInput): Promise&lt;Todo&gt; {<br>    const { title, description } = input;<br>    const todo = new Todo(title, description);<br>    await this.todoRepository.add(todo);<br>    return todo;<br>  }<br>}</pre><p>In this snippet, the CreateTodo class represents the use case for creating a new Todo item. It takes an instance of the TodoRepository interface as a dependency and uses it to persist the created Todo item. The execute method accepts an input object with title and description properties, creates a new Todo instance, adds it to the repository, and returns the created Todo item.</p><ul><li>repositories: This directory contains the repository interfaces for data access. These interfaces define the contract for data persistence, allowing the rest of the application to remain agnostic to the specific data storage implementation. For instance, the todoRepository.ts file defines the interface for Todo repository operations.</li></ul><p>Here&#39;s a snippet of the todoRepository.ts file:</p><pre>import { Todo } from &#39;../domain/entities/todo&#39;;<br><br>export interface TodoRepository {<br>  add(todo: Todo): Promise&lt;void&gt;;<br>  findById(id: string): Promise&lt;Todo | null&gt;;<br>  findAll(): Promise&lt;Todo[]&gt;;<br>  update(todo: Todo): Promise&lt;void&gt;;<br>  delete(id: string): Promise&lt;void&gt;;<br>}</pre><p>In this snippet, the TodoRepository interface specifies the required methods for any Todo repository implementation, such as add, findById, findAll, update, and delete. These methods define the expected behavior for data persistence, allowing the core layer to remain decoupled from the specific data storage technology used in the infrastructure layer.</p><p><strong>Infrastructure Layer</strong></p><p>The infrastructure layer in a Clean Architecture-based application is responsible for providing concrete implementations of interfaces, protocols, or services defined in the core (or domain) layer. It handles interactions with external systems, such as databases, file systems, or third-party services, allowing the core layer to remain agnostic to specific technologies or libraries.</p><p>In the context of our Todo app, the infrastructure layer primarily focuses on the following aspects:</p><ol><li><strong>Data persistence:</strong> The infrastructure layer contains the actual implementation of the repository interfaces defined in the core layer. These implementations use a specific technology or library, such as an ORM (Object-Relational Mapping) like TypeORM, to interact with the data storage system (e.g., a database). By doing this, the infrastructure layer takes care of data storage and retrieval, while the core layer remains decoupled from the specific data storage technology.</li><li><strong>External services:</strong> When an application relies on third-party services, such as sending emails or interacting with APIs, the infrastructure layer is responsible for managing these interactions. It provides concrete implementations for the required services, which can be injected into the core layer as needed.</li><li><strong>Configuration and setup:</strong> The infrastructure layer also handles the configuration of various components, such as setting up a database connection, configuring a web server, or initializing external services. By centralizing these configurations in the infrastructure layer, the core layer remains focused on the business logic and rules.</li></ol><p>In our TypeScript Todo app, the infrastructure layer contains the following components:</p><ul><li>database: This directory contains the database setup and ORM (Object-Relational Mapping) configuration, such as connection.ts. This file will set up the database connection using the TypeORM library and the configuration from database.ts. It will use the provided settings to establish a connection to the database and register the application&#39;s entities.</li></ul><p>Here&#39;s a snippet of the connection.ts file:</p><pre>import { createConnection, Connection } from &#39;typeorm&#39;;<br>import { Todo } from &#39;../core/domain/entities/todo&#39;;<br>import databaseConfig from &#39;../config/database&#39;;<br><br>const connectDatabase = async (): Promise&lt;Connection&gt; =&gt; {<br>  return createConnection({<br>    type: databaseConfig.type as any,<br>    host: databaseConfig.host,<br>    port: databaseConfig.port,<br>    username: databaseConfig.username,<br>    password: databaseConfig.password,<br>    database: databaseConfig.database,<br>    entities: [Todo],<br>    synchronize: true,<br>    logging: false,<br>  });<br>};<br><br>export default connectDatabase;</pre><p>In this snippet, the connectDatabase function sets up the connection to the database using the TypeORM library. It specifies the database type (PostgreSQL in this case), connection details, and the entities to be managed by the ORM. The connectDatabase function returns a Promise that resolves to a Connection object, which can be used throughout the application to interact with the database.</p><ul><li>repositories: This directory contains the implementation of the repository interfaces defined in the core layer. These implementations handle the actual persistence of data in the chosen storage solution. For example, todoRepositoryImpl.ts is the implementation of the Todo repository interface, handling the actual data persistence using the ORM.</li></ul><p>Here&#39;s a snippet of the todoRepositoryImpl.ts file:</p><pre>import { Repository, EntityRepository } from &#39;typeorm&#39;;<br>import { Todo } from &#39;../../core/domain/entities/todo&#39;;<br>import { TodoRepository } from &#39;../../core/repositories/todoRepository&#39;;<br><br>@EntityRepository(Todo)<br>export class TodoRepositoryImpl extends Repository&lt;Todo&gt; implements TodoRepository {<br>  async add(todo: Todo): Promise&lt;void&gt; {<br>    await this.save(todo);<br>  }<br><br>  async findById(id: string): Promise&lt;Todo | null&gt; {<br>    return this.findOne(id);<br>  }<br><br>  async findAll(): Promise&lt;Todo[]&gt; {<br>    return this.find();<br>  }<br><br>  async update(todo: Todo): Promise&lt;void&gt; {<br>    await this.save(todo);<br>  }<br><br>  async delete(id: string): Promise&lt;void&gt; {<br>    await this.delete(id);<br>  }<br>}</pre><p>In this snippet, the TodoRepositoryImpl class extends the TypeORM Repository class and implements the TodoRepository interface. It provides the actual implementation of the methods defined in the TodoRepository interface, such as add, findById, findAll, update, and delete. These methods interact with the ORM to perform the necessary data persistence operations.</p><p><strong>Application Layer</strong></p><p>The application layer handles the interaction between the user and the application. It is composed of:</p><ul><li>controllers: This directory contains the API controllers, which manage the communication between the client (e.g., a web or mobile app) and the application. Controllers handle user input, invoke the appropriate use cases, and return the results. For example, todoController.ts contains the logic for managing Todo-related API requests.</li></ul><p>Here&#39;s a snippet of the todoController.ts file:</p><pre>import { FastifyRequest, FastifyReply } from &#39;fastify&#39;;<br>import { CreateTodo } from &#39;../../core/use-cases/createTodo&#39;;<br>import { TodoRepositoryImpl } from &#39;../../infrastructure/repositories/todoRepositoryImpl&#39;;<br><br>const todoRepository = new TodoRepositoryImpl();<br><br>export const createTodo = async (req: FastifyRequest, res: FastifyReply): Promise&lt;void&gt; =&gt; {<br>  try {<br>    const { title, description } = req.body;<br>    const createTodoUseCase = new CreateTodo(todoRepository);<br>    const newTodo = await createTodoUseCase.execute({ title, description });<br><br>    res.status(201).send({<br>      success: true,<br>      data: newTodo,<br>    });<br>  } catch (error) {<br>    res.status(400).send({<br>      success: false,<br>      message: error.message,<br>    });<br>  }<br>};<br><br>// Additional controller methods for handling other Todo-related API requests</pre><p>In this snippet, the createTodo function serves as the controller for creating a new Todo item using Fastify. It extracts the required data from the req.body object, creates an instance of the CreateTodo use case, and invokes its execute method. The resulting newTodo object is then sent back to the client using Fastify&#39;s res.send() method with a status code of 201. Error handling is incorporated to ensure that any issues encountered during the process are communicated back to the client with an appropriate status code and error message. This controller can be extended with additional methods for handling other Todo-related API requests.</p><ul><li>dtos (Data Transfer Objects): This directory contains data transfer objects for input validation and output formatting. DTOs provide a standardized way to send and receive data between the client and the application. For example, createTodoDTO.ts and updateTodoDTO.ts define the structure and validation rules for creating and updating todos.</li></ul><p>Here&#39;s a snippet of the createTodoDTO.ts file:</p><pre>import { IsString, IsNotEmpty, MaxLength } from &#39;class-validator&#39;;<br><br>export class CreateTodoDTO {<br>  @IsString()<br>  @IsNotEmpty()<br>  @MaxLength(100)<br>  title: string;<br><br>  @IsString()<br>  @IsNotEmpty()<br>  @MaxLength(500)<br>  description: string;<br>}</pre><p>In this snippet, the CreateTodoDTO class defines the structure and validation rules for creating a new Todo item. The title and description properties are decorated with validation decorators from the class-validator library, such as IsString, IsNotEmpty, and MaxLength. These decorators help ensure that the input data received from the client conforms to the expected format and constraints before being processed by the application.</p><p><strong>Config Layer</strong></p><p>The config layer contains the configuration files and constants for the application, such as:</p><ul><li>app.ts: This file contains the main application configuration, such as setting up the Fastify app, routes, and middleware.</li></ul><p>Here’s a snippet of the app.ts file:</p><pre>// src/config/app.ts<br><br>import fastify, { FastifyInstance } from &#39;fastify&#39;;<br>import cors from &#39;fastify-cors&#39;;<br>import helmet from &#39;fastify-helmet&#39;;<br>import connectDatabase from &#39;../infrastructure/database/connection&#39;;<br>import { todoController } from &#39;../application/controllers/todoController&#39;;<br><br>const app: FastifyInstance = fastify({ logger: true });<br><br>// Middleware<br>app.register(cors);<br>app.register(helmet);<br><br>// Connect to the database<br>connectDatabase().then(() =&gt; {<br>  app.log.info(&#39;Database connected&#39;);<br>}).catch((error) =&gt; {<br>  app.log.error(&#39;Database connection failed:&#39;, error);<br>});<br><br>// Routes<br>app.get(&#39;/todos&#39;, todoController.getTodos);<br>app.post(&#39;/todos&#39;, todoController.createTodo);<br>app.put(&#39;/todos/:id&#39;, todoController.updateTodo);<br>app.delete(&#39;/todos/:id&#39;, todoController.deleteTodo);<br><br>// Error handling<br>app.setErrorHandler((error, request, reply) =&gt; {<br>  app.log.error(error);<br>  reply.status(500).send(&#39;Internal Server Error&#39;);<br>});<br><br>export default app;</pre><p>In this example, the app.ts file starts by importing the necessary packages and modules, such as Fastify, CORS, Helmet, and the Todo controller. The file then initializes a Fastify instance and sets up the middleware.</p><p>Next, the file connects to the database using the connectDatabase function from database/connection.ts.</p><p>After setting up the middleware and connecting to the database, the file defines the routes for the Todo app, using the methods from the todoController as handlers for each route.</p><p>Finally, the app.ts file sets up basic error handling to log errors and respond with a 500 status code for internal server errors. The Fastify instance is then exported for use in other parts of the application, such as starting the server.</p><ul><li>database.ts: This file will contain the configuration settings for the database connection, such as database type, host, port, username, and password. These settings can be extracted from environment variables or a configuration file.</li></ul><p>Here&#39;s a snippet of the database.ts file:</p><pre>interface DatabaseConfig {<br>  type: string;<br>  host: string;<br>  port: number;<br>  username: string;<br>  password: string;<br>  database: string;<br>}<br><br>const databaseConfig: DatabaseConfig = {<br>  type: process.env.DB_TYPE || &#39;postgres&#39;,<br>  host: process.env.DB_HOST || &#39;localhost&#39;,<br>  port: Number(process.env.DB_PORT) || 5432,<br>  username: process.env.DB_USERNAME || &#39;your_username&#39;,<br>  password: process.env.DB_PASSWORD || &#39;your_password&#39;,<br>  database: process.env.DB_NAME || &#39;todo_app&#39;,<br>};<br><br>export default databaseConfig;</pre><p>In this snippet, the connectDatabase function sets up the connection to the database using the TypeORM library. It specifies the database type (PostgreSQL in this case), connection details, and the entities to be managed by the ORM. The connectDatabase function returns a Promise that resolves to a Connection object, which can be used throughout the application to interact with the database.</p><p><strong>Tests</strong></p><p>The tests directory contains unit and integration tests for the application, grouped by their respective layers. These tests ensure the correct functioning of the application and can help identify issues early in the development process. For example:</p><ul><li>core: Contains tests for the domain entities and repository interfaces.</li><li>infrastructure: Contains tests for the infrastructure layer, such as database and ORM configurations, and repository implementations.</li><li>application: Contains tests for the application layer, such as controllers and DTOs.</li></ul><h3>Conclusion</h3><p>In this article, we have taken a detailed look at the directory structure and its contents when creating a Todo app using TypeScript and Clean Architecture. By following these guidelines, you can create a solid foundation for your TypeScript application and ensure its long-term success.</p><p>The Clean/Hexagonal Architecture allows you to keep a separation of concerns and maintain a highly testable and maintainable codebase. This architecture enables developers to quickly adapt to changes and scale the application as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e177f9f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring a custom domain for AWS Lambda Function URLs]]></title>
            <link>https://medium.com/@walid.karray/configuring-a-custom-domain-for-aws-lambda-function-url-with-serverless-framework-c0d78abdc253?source=rss-aaefb44882c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d78abdc253</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[custom-domain]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[cloudfront]]></category>
            <dc:creator><![CDATA[Walid Karray]]></dc:creator>
            <pubDate>Sat, 07 May 2022 23:53:08 GMT</pubDate>
            <atom:updated>2022-05-08T00:41:31.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*IQwfZw_lzU_S8rwHruoMIw.png" /></figure><blockquote>This post assumes you have working knowledge of AWS Lambda and Serverless Framework.</blockquote><p>06 APR 2022 — AWS announced an exciting news of Built-in HTTPS Endpoints for Lambda functions. You can read the <a href="https://aws.amazon.com/fr/blogs/aws/announcing-aws-lambda-function-urls-built-in-https-endpoints-for-single-function-microservices/">original post </a>.</p><p>Before this announcement, to expose an HTTP endpoint with a custom domain for your lambda backend you have to use the following AWS resources:</p><ul><li>Lambda (application backend)</li><li>API Gateway (to expose HTTP endpoint)</li><li>Cloudfront distribution</li><li>Route 53</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Odw0bo4xnVGt616IrZj3qQ.png" /><figcaption>Custom domain API endpoint architecture without Lambda Function URLs</figcaption></figure><p>Fortunately, with AWS Lambda URLs you no longer need the API Gateway !</p><p>This is how it looks the new architecture :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*L5SZ1jEC5Vp1fgGA0e9A6w.png" /><figcaption>Custom domain API endpoint architecture with Lambda Function URLs</figcaption></figure><p><strong>Let’s deep dive into the subject …</strong></p><p>In this section, we will create and deploy a<em> “Hello World” </em>HTTP endpoint with a custom domain using Lambda Function URLs !</p><p><strong><em>Note:</em></strong> In this tutorial I have used Javascript for Lambda handler and Serverless framework as IaC.</p><p>As a first step, you need to install serverless framework.</p><pre>$ mkdir lambda-function-url-custom-domain<br>$ cd ./lambda-function-url-custom-domain</pre><pre>$ yarn add -D serverless</pre><p>Create a <strong>serverless.yaml </strong>file<strong> </strong>with the following content :</p><pre>service: lambda-function-url-custom-domain<br>frameworkVersion: &#39;3&#39;<br><br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  region: ${opt:region, &#39;eu-west-1&#39;}<br>  lambdaHashingVersion: &#39;20201221&#39;<br><br>custom:<br>  apiDomain: api.example.com  # change by your custom domain<br>  hostedZoneName: example.com.  # your domain Route 53 hosted zone name<br>  certificateNVirginaArn: arn:aws:acm:us-east-1:xxxxxx:certificate/xxxxxxx # change by your certificate ARN (should be in North Virginia region)<br><br>functions:<br>  api:<br>    handler: lambda.handler<br>    url: true # needed to expose lambda function url !<br><br>resources:<br>  Resources:<br>    ApiCloudFrontDistribution:<br>      Type: AWS::CloudFront::Distribution<br>      DeletionPolicy: Delete<br>      Properties:<br>        DistributionConfig:<br>          Enabled: true<br>          PriceClass: PriceClass_100<br>          HttpVersion: http2<br>          Comment: Api distribution for ${self:custom.apiDomain}<br>          Origins:<br>            - Id: ApiGateway<br>              DomainName: !Select [2, !Split [&quot;/&quot;, !GetAtt ApiLambdaFunctionUrl.FunctionUrl]] # extract function url form your lambda resource<br>              OriginPath: &#39;&#39;<br>              CustomOriginConfig:<br>                HTTPPort: 80<br>                HTTPSPort: 443<br>                OriginProtocolPolicy: https-only<br>                OriginSSLProtocols: [TLSv1, TLSv1.1, TLSv1.2]<br>          DefaultCacheBehavior:<br>            TargetOriginId: ApiGateway<br>            ViewerProtocolPolicy: redirect-to-https<br>            Compress: true<br>            DefaultTTL: 0<br>            AllowedMethods:<br>              - HEAD<br>              - DELETE<br>              - POST<br>              - GET<br>              - OPTIONS<br>              - PUT<br>              - PATCH<br>            CachedMethods:<br>              - HEAD<br>              - OPTIONS<br>              - GET<br>            ForwardedValues:<br>              QueryString: false<br>              Headers:<br>                - Accept<br>                - x-api-key<br>                - Authorization<br>              Cookies:<br>                Forward: none<br>          Aliases:<br>            - ${self:custom.apiDomain}<br>          ViewerCertificate:<br>            SslSupportMethod: sni-only<br>            MinimumProtocolVersion: TLSv1.2_2019<br>            AcmCertificateArn: ${self:custom.certificateNVirginaArn}<br>    ApiRecordSetGroup:<br>      Type: AWS::Route53::RecordSetGroup<br>      DeletionPolicy: Delete<br>      DependsOn:<br>        - ApiCloudFrontDistribution<br>      Properties:<br>        HostedZoneName: ${self:custom.hostedZoneName}<br>        RecordSets:<br>          - Name: ${self:custom.apiDomain}<br>            Type: A<br>            AliasTarget:<br>              HostedZoneId: Z2FDTNDATAQYW2 # Cloudfront default hosted zone ID<br>              DNSName: { &#39;Fn::GetAtt&#39;: [ApiCloudFrontDistribution, DomainName] } # set the domain of your cloudfront distribution</pre><p>First of all you need to configure parameters in the <strong>custom</strong> section :</p><ul><li><strong>apiDomain:</strong> a custom domain for your backend/api endpoint</li><li><strong>hostedZoneName:</strong> Route 53 hosted zone name of your domain name (please note that a hosted zone name should ends with a “.”)</li><li><strong>certificateNVirginiaArn:</strong> Certificate ARN to use with CloudFront, it should be created only in US East (N. Virginia) region.</li></ul><p>As you can see we have the following 3 resources :</p><ul><li>A Lambda function: You should note that once the resource is created AWS will attribute a random url it looks like this : <a href="https://oydnwyle2uxj7rtkmro4665qca0otptu.lambda-url.eu-west-1.on.aws/">https://oydnwyle2uxj7rtkmro4234qca0otptu.lambda-url.eu-west-1.on.aws/</a></li><li>A Cloudfront distribution <strong>ApiCloudFrontDistribution</strong> which handles all incoming traffic to the origin “your <strong>Lambda</strong> function URL endpoint” .<br>In order to set the Cloudfront Origin domain name by the generated Lambda function url domain, you need to use this CloudFormation syntax :</li></ul><pre>!Select [2, !Split [“/”, !GetAtt ApiLambdaFunctionUrl.FunctionUrl]] # extract function url form your lambda resource</pre><p>In our project, the name of the lambda function is “api” so the Lambda resource name should be “ApiLambdaFunctionUrl”. If for instance your function name is “backend” It will be “BackendLambdaFunctionUrl”.</p><ul><li>A Route 53 RecordSetGroup <strong>ApiRecordSetGroup</strong> to setup an alias “A” record “<strong>api.example.com”</strong> that routes traffic to our Cloudfront Distribution</li></ul><p>Next, we need to create our Lambda function that returns the following message<em> ‘Hello from Lambda Function URLs !’</em> with a 200 (OK) as HTTP status code.</p><p><strong>lambda.js</strong></p><pre>exports.handler = async (event) =&gt; {<br>    return {<br>        statusCode: 200,<br>        body: &#39;Hello from Lambda Function URLs !&#39;,<br>    };<br>};</pre><p>The final step is to deploy</p><pre>$ sls deploy</pre><p>As you can see, when deployment finished, the function URL will be displayed in console output. Note that is the random attributed Lambda URL endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*Ah5hDwe5m1YS4e81a5HELw.png" /></figure><p>But don’t worry ! Everything should be fine with your custom endpoint.<br>Juste copy-paste your custom endpoint in a web browser and you should get response displayed from your lambda handler like shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*bs1s8e9XhlKBDV9jFMMAtg.png" /></figure><p>If it didn’t work and you got and error like DNS_PROBE_FINISHED_NXDOMAIN, wait a while and check again, it’s due to DNS propagation delay.</p><p><strong>Conclusion</strong></p><p>So in this way you are able to deploy a serverless application with a custom domain using only <strong>Lambda + Cloudfront + Route 53, </strong>thanks to Lambda Function URLs.</p><p>The source code of this tutorial can be accessed on GitHub from this <a href="https://github.com/tux86/lambda-function-url-custom-domain">link</a>.</p><p>You can read more about function URLs from this interesting article : <a href="https://lumigo.io/blog/aws-lambda-function-url-is-live/">https://lumigo.io/blog/aws-lambda-function-url-is-live/</a></p><blockquote><em>Thanks for reading!</em></blockquote><blockquote><em>If you like the above article please clap the same and if you don’t like please put your thoughts in comments so that I can improve it.</em></blockquote><blockquote><em>You can reach me out on </em><a href="https://www.linkedin.com/in/karray/"><em>Linkedin</em></a><em>, </em><a href="https://github.com/tux86"><em>G</em>ithub</a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d78abdc253" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>