<?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[Full Stack Wizardry - Medium]]></title>
        <description><![CDATA[Engineering everything from atoms to algorithms. - Medium]]></description>
        <link>https://medium.com/full-stack-engineer?source=rss----8f1c7cdc1132---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Full Stack Wizardry - Medium</title>
            <link>https://medium.com/full-stack-engineer?source=rss----8f1c7cdc1132---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:24:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/full-stack-engineer" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Install a Swift Formatter in VSCode]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-install-a-swift-formatter-in-vscode-c3e62b034dca?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3e62b034dca</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[formatting]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 20:27:20 GMT</pubDate>
            <atom:updated>2026-02-24T20:27:56.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how you can get the standard Swift formatting tool installed in VSCode and auto-format your .swift files.</h4><p>This simple process will help you stay in lovely VSCode and away from horrible Xcode. It’s a quick fix; let’s do it.</p><h3>Step 1 — Install swift-format</h3><p>If you don’t already have Homebrew installed, you can <a href="https://brew.sh/">get it here</a>. Run the following command from your terminal:</p><pre>brew install swift-format</pre><p>This installs the following package:</p><p><a href="https://formulae.brew.sh/formula/swift-format">swift-format</a></p><p>This package does all of the heavy lifting. It’s an opinionated formatter released by the Swift-lang team.</p><h3>Step 2 — Add the apple-swift-format Extension</h3><p>Next, you need an extension in VSCode that can use that package. So install the following extension:</p><p><a href="https://marketplace.visualstudio.com/items?itemName=vknabel.vscode-apple-swift-format">apple-swift-format - Visual Studio Marketplace</a></p><p>This extension is able to see swift-format and call it on your .swift files.</p><h3>Step 3 — Update Your settings.json</h3><p>Now you have the correct extension installed, open your settings.json file in VSCode by pressing: cmd+shift+p. Then typing “<em>settings”</em>. This will show you the following option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*QEMBavU7O9sSm9AYKy7plw.png" /><figcaption>The user settings pop up menu.</figcaption></figure><p>Click on the top one.</p><p>Paste the following options into the file:</p><pre>{<br>  // ... (other settings)<br>  &quot;[swift]&quot;: {<br>    &quot;editor.defaultFormatter&quot;: &quot;vknabel.vscode-apple-swift-format&quot;,<br>    &quot;editor.formatOnSave&quot;: true,<br>  },<br>  // ... (other settings)<br>}</pre><p>This sets the correct formatter and tells VSCode to format your file when you save it. Format-on-save is optional; I just happen to like it.</p><h3>Final Words</h3><p>That’s it! I hope this helps my fellow VSCode lovers develop in Swift without changing their favourite IDE. Manual formatting sucks, opinionated formatting rules. Enjoy 😁</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3e62b034dca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-install-a-swift-formatter-in-vscode-c3e62b034dca">How To Install a Swift Formatter in VSCode</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Intellisense Work for a Swift Project in VSCode]]></title>
            <link>https://medium.com/full-stack-engineer/make-intellisense-work-for-a-swift-project-in-vscode-ff49d10aefcd?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/ff49d10aefcd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[intellisense]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 22:29:37 GMT</pubDate>
            <atom:updated>2026-02-13T10:47:23.868Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use the official Swift VSCode plugin and a dev server to get proper Swift intellisense for your XCode project.</h4><p>In this tutorial, you will:</p><ol><li>Install the official Swift plugin for VSCode.</li><li>Install and run <a href="https://github.com/SolaWing/xcode-build-server">xcode-build-server</a>.</li><li>Use the <a href="https://build-server-protocol.github.io/">build-server</a> to communicate with the Swift Language Server Protocol and get Intellisense working properly.</li></ol><p>Meaning you don’t have to leave lovely VSCode for crappy XCode when you’re building macOS apps.</p><h3>Step 1 — Install the Official Swift Plugin</h3><p>Install the following plugin in VSCode:</p><p><a href="https://marketplace.visualstudio.com/items?itemName=swiftlang.swift-vscode">Swift - Visual Studio Marketplace</a></p><p>When you search the marketplace, you’ll likely see two. Search this exact string to get the correct one:</p><pre>swiftlang.swift-vscode</pre><h3>Step 2 — Install xcode-build-server</h3><p>You can install <a href="https://formulae.brew.sh/formula/xcode-build-server">xcode-build-server</a> via <a href="https://formulae.brew.sh/">brew</a> with:</p><pre>brew install xcode-build-server</pre><p>This will install it as a CLI command. Check it’s worked with:</p><pre>where xcode-build-server</pre><h3>Step 3 — Build Your Project with XCode</h3><p>To build your project, run the following:</p><pre>xcodebuild -scheme YourScheme -destination &#39;platform=macOS&#39; clean build </pre><p>The -scheme flag tells XCode which set of build instructions you want to run. You can see the available schemes by running the following from the root of your project:</p><pre>xcodebuild -list</pre><h3>Step 4 — Run xcode-build-server</h3><p>Finally, you can run the xcode-build-server to produce a buildServer.json file that tells the LSP how to interact with the xcode-build-server:</p><pre>xcode-build-server config -project YourProject.xcodeproj -scheme YourScheme</pre><p>This will create a buildServer.json file that looks like this:</p><pre>{<br> &quot;name&quot;: &quot;xcode build server&quot;,<br> &quot;version&quot;: &quot;1.3.0&quot;,<br> &quot;bspVersion&quot;: &quot;2.2.0&quot;,<br> &quot;languages&quot;: [<br>  &quot;c&quot;,<br>  &quot;cpp&quot;,<br>  &quot;objective-c&quot;,<br>  &quot;objective-cpp&quot;,<br>  &quot;swift&quot;<br> ],<br> &quot;argv&quot;: [<br>  &quot;/opt/homebrew/bin/xcode-build-server&quot;<br> ],<br> &quot;workspace&quot;: &quot;/Users/your-username/path/to/your-project/YourProject.xcodeproj/project.xcworkspace&quot;,<br> &quot;build_root&quot;: &quot;/Users/your-username/Library/Developer/Xcode/DerivedData/YourProject-dkymfthsnwjywxatlrxebnqpfpav&quot;,<br> &quot;scheme&quot;: &quot;YourScheme&quot;,<br> &quot;kind&quot;: &quot;xcode&quot;<br>}</pre><p>This configuration tells the Swift LSP to call the xcode-build-server program we’ve installed via brew with the workspace, build_root, and scheme provided. xcode-build-server looks at the build logs and finds out what files XCode built with what. These are returned to the Swift LSP to allow proper intellisense.</p><h4>Multiple Schemes</h4><p>If you have multiple Schemes in your project definition, you’ll have to run the xcode-build-server command on the different Schemes in turn. You will then get Intellisense on the built Scheme, but not on the unbuilt ones. Change the scheme option in the buildServer.json to alter what Scheme you want Intellisense on.</p><h3>Final Words</h3><p>I’m brand new to Swift development, so I apologise if I’m overlooking anything in this tutorial. However, I couldn’t find a decent tutorial explaining how to set up Intellisense in VSCode properly, so I had to make one.</p><p>I hope it saves you the 2.5 hours I spent searching and hacking for a working solution! Swift away.</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff49d10aefcd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/make-intellisense-work-for-a-swift-project-in-vscode-ff49d10aefcd">Make Intellisense Work for a Swift Project in VSCode</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Force Run a Firebase Function Cron Job]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-force-run-a-firebase-function-cron-job-f39111ff4e32?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/f39111ff4e32</guid>
            <category><![CDATA[firebase-functions]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 16:16:08 GMT</pubDate>
            <atom:updated>2026-02-04T16:16:07.555Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to manually run a live Firebase Function cron job using Google Cloud Scheduler.</h4><p>In this tutorial, you will learn how to manually trigger a live Firebase Function cron job. You can do this in two ways:</p><ol><li>Via the Firebase Console web platform.</li><li>Via the gcloud CLI.</li></ol><p>I will explain both.</p><h3>Method 1 — Trigger via the Firebase Console</h3><p>Visit the <a href="https://console.firebase.google.com/">Firebase console</a> to see all of your functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2KNvKIO-frdPZR4sDVWTg.png" /><figcaption>An example of my Firebase Functions dashboard, the Cron Job function is not shown in the image.</figcaption></figure><p>Click the triple-dot options button on your chosen function, and then select View in Cloud Scheduler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*1CEDGkelIHkOK73WkK5dNw.png" /><figcaption>The popup box after clicking the cron job triple-dot drop down with View in Cloud Scheduler highlighted.</figcaption></figure><p>You will see the following interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUHF5U4MNUnFidvrXaxvOg.png" /><figcaption>The Cloud Scheduler job interface for my Firebase Project.</figcaption></figure><p>Click the triple-dot button on the far right of the function you want to force run. It will be in the Actions column. Select the Force run option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRRyxG7chVMhcva3UTHLJA.png" /><figcaption>The pop up box that appears when you click on a scheduler actions drop down.</figcaption></figure><p>This will run your cron job as if it were triggered by the standard trigger. You can check your Function’s logs to see the output.</p><h3>Method 2 — Trigger via the gcloud CLI</h3><p>If you don’t have the gcloud CLI tool, you can download it here:</p><p><a href="https://docs.cloud.google.com/sdk/docs/install-sdk">Quickstart: Install the Google Cloud CLI | Google Cloud SDK | Google Cloud Documentation</a></p><p>Once you have the tool, check what jobs you can run:</p><pre>gcloud scheduler jobs list --location=europe-west1 --project=&lt;project-id&gt;</pre><p>The flag values have the following meaning:</p><ul><li>&lt;region&gt; — Replace this with the region of your project, i.e. europe-west1.</li><li>&lt;project-id&gt; — Replace this with the ID of your Project. Without this, gcloud will use whatever project you currently have set. If this is already the correct project, you can remove this flag.</li></ul><p>If you don’t know your Project ID, you can find it with the <a href="https://www.npmjs.com/package/firebase-tools">Firebase CLI</a>:</p><pre>firebase projects:list</pre><p>Run the query, and you’ll get output similar to the following:</p><pre>ID                                        LOCATION      SCHEDULE (TZ)    TARGET_TYPE  STATE<br>firebase-schedule-some-func-europe-west1  europe-west1  0 1 * * * (UTC)  HTTP         ENABLED</pre><p>Copy the ID of the function, in this case: firebase-schedule-some-func-europe-west1. Then run the following:</p><pre>gcloud scheduler jobs run &lt;job-id&gt; --location=&lt;region&gt; --project=&lt;project-id&gt;</pre><p>As an example, mine would look like this:</p><pre>gcloud scheduler jobs run firebase-schedule-some-func-europe-west1 --location=europe-west1 --project=myProject123</pre><h4>Check logs in the terminal</h4><p>If you live in the terminal, you can check the cron job has worked by tailing the logs with the <a href="https://www.npmjs.com/package/firebase-tools">Firebase CLI</a>, like this:</p><pre>firebase functions:log --only &lt;function-name&gt;</pre><h3>Final Words</h3><p>I hope this saves you the frustrating 5-minute <em>“how do I do that again?”</em> when you come to your cron job tests. Happy cronn’ing!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39111ff4e32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-force-run-a-firebase-function-cron-job-f39111ff4e32">How To Force Run a Firebase Function Cron Job</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Run Drizzle ORM on a D1 Database in Cloudflare Pages SvelteKit Application]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-run-drizzle-orm-on-a-d1-database-in-cloudflare-pages-sveltekit-application-a14ec08e723e?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/a14ec08e723e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[drizzle]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[sveltekit]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 23:37:23 GMT</pubDate>
            <atom:updated>2026-08-10T21:28:30.243Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to set up Drizzle ORM to build a schema for your D1 database in Cloudflare and build a simple project with it.</h4><p>In this tutorial, you will learn:</p><ol><li>How to set up Drizzle ORM in a pre-existing Cloudflare Pages SvelteKit application bound to a D1 Database.</li><li>How to generate and apply migrations to your D1 database.</li><li>How to use Drizzle ORM in your application.</li></ol><p>The tutorial focuses on adding Drizzle ORM to a pre-existing project. If you’re starting from scratch, use <a href="https://svelte.dev/docs/cli/sv-create">sv create</a> and select it as a dependency during setup.</p><h3>Prerequisites</h3><p>To complete this tutorial, you need:</p><ol><li>A preexisting Cloudflare Pages SvelteKit application bound to a D1 Database.</li><li>The <a href="https://developers.cloudflare.com/workers/wrangler/">wrangler</a> CLI.</li></ol><p>There’s a lot hidden in the first prerequisite. Read how to add a D1 Database here:</p><p><a href="https://medium.com/full-stack-engineer/use-a-d1-sqlite-database-in-a-cloudflare-pages-sveltekit-application-3b32c8c60556">Use a D1 Database in a Cloudflare Pages SvelteKit Application</a></p><h3>Step 1 — Set up Drizzle ORM</h3><p>First, install <a href="https://orm.drizzle.team/docs/overview">drizzle-orm</a> and <a href="https://orm.drizzle.team/docs/kit-overview">drizzle-kit</a> with the following command:</p><pre>npm install drizzle-orm<br>npm install -D drizzle-kit</pre><p>The drizzle-orm package will be used directly in your application as the wrapper layer for your database. The drizzle-kit package is local and is used to manage migrations.</p><h4>Define your schema</h4><p>Set up your schema.ts file inside of the lib directory of your SvelteKit project with:</p><pre>mkdir -p src/lib/server/db<br>touch src/lib/server/db/schema.ts</pre><p>This is where you’ll define your <a href="https://en.wikipedia.org/wiki/Database_schema">database schema</a>. You can learn how to define your schema <a href="https://orm.drizzle.team/docs/sql-schema-declaration">here</a>. The schema below is an example we’ll use later in the tutorial:</p><pre>import { sqliteTable, text, integer } from &#39;drizzle-orm/sqlite-core&#39;;<br><br>export const visitors = sqliteTable(&#39;visitors&#39;, {<br> id: integer(&#39;id&#39;).primaryKey({ autoIncrement: true }),<br> country: text(&#39;country&#39;), // &quot;US&quot;, &quot;GB&quot;, etc.<br> city: text(&#39;city&#39;), // &quot;New York&quot;, &quot;London&quot;<br> timestamp: integer(&#39;timestamp&#39;, { mode: &#39;timestamp&#39; }).notNull()<br>});</pre><h4>Add the configuration</h4><p>Next, add the drizzle kit config file to your root directory with:</p><pre>touch drizzle.config.ts</pre><p>Then paste in the following:</p><pre>import { defineConfig } from &#39;drizzle-kit&#39;;<br><br>export default defineConfig({<br> schema: &#39;./src/lib/server/db/schema.ts&#39;, // Point to your schema file<br> out: &#39;./drizzle&#39;, // Where SQL migrations will be saved<br> dialect: &#39;sqlite&#39; // D1 is SQLite-based<br>});</pre><p>This tells drizzle-kit commands where to find your schema, where migrations are stored, and how to generate them. Don’t worry about creating the /drizzle directory at the root; it happens automatically.</p><h3>Step 2 — Integrate Drizzle Kit with D1</h3><p>In the <a href="https://orm.drizzle.team/docs/guides/d1-http-with-drizzle-kit">Drizzle Kit docs</a>, they tell you to migrate changes directly to Cloudflare. To do so, you need to collect and manage environment variables. <strong><em>Don’t do this</em></strong>, there’s a cleaner way with Cloudflare&#39;s <a href="https://developers.cloudflare.com/workers/wrangler/">wrangler</a> tool.</p><p>Add the following scripts to package.json:</p><pre>{<br>  // ... <br>  &quot;scripts&quot;: {<br>    // ... <br>    &quot;db:generate&quot;: &quot;drizzle-kit generate&quot;,<br>    &quot;db:migrate:local&quot;: &quot;wrangler d1 migrations apply &lt;db-binding-name&gt; --local&quot;,<br>    &quot;db:migrate:prod&quot;: &quot;wrangler d1 migrations apply &lt;db-binding-name&gt; --remote&quot;,<br>    // ...<br>  },<br>  // ... <br>}</pre><p>Make sure you replace: &lt;db-binding-name&gt; with the binding name of your D1 Database in your wrangler config file. For example, a commonly recommended binding is DB.</p><p>You’ll see how these scripts work in a moment.</p><p>Next, update your wrangler.jsonc database config to this:</p><pre>{<br>  &quot;d1_databases&quot;: [<br>    {<br>     &quot;binding&quot;: &quot;DB&quot;,<br>     &quot;database_name&quot;: &quot;database-prod&quot;,<br>     &quot;database_id&quot;: &quot;ecaf2fd9-9asdfh-ash9-a6c868fe6b78&quot;,<br>     &quot;migrations_dir&quot;: &quot;./drizzle&quot; // Add this option in<br>    }<br>   ],<br>}</pre><p>Or if you’re using a .toml file, do this:</p><pre>[[ d1_databases ]]<br>binding=&quot;DB&quot;<br>database_name=&quot;database-prod&quot;<br>database_id=&quot;ecaf2fd9-9asdfh-ash9-a6c868fe6b78&quot;<br>migrations_dir=&quot;./drizzle&quot; # Add this option in</pre><p>This tells wrangler you’re using migrations to manage the database, and they can be found in the ./drizzle directory. You can read <a href="https://developers.cloudflare.com/d1/reference/migrations/#wrangler-customizations">this resource</a> for more information.</p><h4>The one downside</h4><p>You can’t use drizzle-kit studio with this method.</p><h3>Step 3 — Working With Migrations</h3><p>I’ll break down the workflow into several stages.</p><h4>Generate a migration</h4><p>Let’s generate the initial migration. There are two ways to do this:</p><pre>npm run db:generate</pre><p>or</p><pre>npm run db:generate -- --name &lt;your-migration-name&gt;</pre><p>The first one will generate a random name like:</p><ul><li>0000_jazzy_tarot.sql</li><li>0000_good_nicolaos.sql</li></ul><p>These are the first two I generated. As you can see, the prefix 0000_ is always there, which remains the case in either method and should be left for ordering.</p><p>In the second method, you choose the name. For example:</p><pre>npm run db:generate -- --name initial</pre><p>Produces: 0000_initial.sql. Giving migrations a meaningful name is considered good practice, particularly as you commit them, track them, and onboard people to your schema.</p><p>Whatever method you choose, if you use the Visitor schema.ts provided above, your migration file should look like this:</p><pre>CREATE TABLE `visitors` (<br> `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,<br> `country` text,<br> `city` text,<br> `timestamp` integer NOT NULL<br>);</pre><p>And you should now have ./drizzle directory with this structure:</p><pre>📁 drizzle/<br>├── 📄 0000_initial.sql<br>├── 📁 meta/<br>│   ├── 📄 0000_snapshot.json<br>│   └── 📄 _journal.json</pre><h4>Applying a local migration</h4><p>In the scripts, you will have seen local and production migration options. This is one of the best bits of using wrangler for migrations, there is no configuration swap. You can easily push to both with simple commands.</p><p>Let’s start by updating the local database with:</p><pre>npm run db:migrate:local</pre><p>This will show you output like the following:</p><pre>➜  full-stack-gaming git:(feat/add-drizzle-orm) ✗ npm run db:migrate:local<br><br>&gt; full-stack-gaming@0.0.1 db:migrate:local<br>&gt; wrangler d1 migrations apply DB --local<br><br><br> ⛅️ wrangler 4.47.0 (update available 4.60.0)<br>─────────────────────────────────────────────<br>Resource location: local <br><br>Use --remote if you want to access the remote instance.<br><br>Migrations to be applied:<br>┌────────────────────────┐<br>│ name                   │<br>├────────────────────────┤<br>│ 0000_initial.sql       │<br>└────────────────────────┘<br>✔ About to apply 1 migration(s)<br>Your database may not be available to serve requests during the migration, continue? … yes<br>🌀 Executing on local database DB (ecaf2fd9-9asdfh-ash9-a6c868fe6b78) from .wrangler/state/v3/d1:<br>🌀 To execute on your remote database, add a --remote flag to your wrangler command.<br>🚣 2 commands executed successfully.<br>┌────────────────────────┬────────┐<br>│ name                   │ status │<br>├────────────────────────┼────────┤<br>│ 0000_initial.sql       │ ✅     │<br>└────────────────────────┴────────┘</pre><p>You can check this has worked by inspecting the SQLite database stored in the following directory:</p><pre>.wrangler/state/v3/d1/miniflare-D1DatabaseObject</pre><p>The data is stored as binary, so you’ll need a special tool do this. One such tool is the <a href="https://marketplace.visualstudio.com/items?itemName=qwtel.sqlite-viewer">SQLite Viewer</a>, available in VSCode and forks (Cursor etc.).</p><h4>Tidying up local</h4><p>After you’ve finished testing locally, you may want to delete the test migrations you’ve made and the tables they’ve created.</p><p>You can do this by first going into drizzle/meta/_journal.json and deleting the entry for your migrations. Then deleting the corresponding snapshot, which will have the same prefix as the migration. For example: 0000_.</p><p>Finally, you can run the following commands:</p><pre>rm drizzle &lt;your-migration&gt;.sql<br>npx wrangler d1 execute &lt;db-binding&gt; --local --command &quot;DROP TABLE d1_migrations&quot;<br>npx wrangler d1 execute &lt;db-binding&gt; --local --command &quot;DROP TABLE visitors&quot;</pre><p>You can extend this to drop as many test tables as you like.</p><blockquote>You don’t have to drop the d1_migrations table, you could remove rows if you like.</blockquote><h4>Applying a production migration</h4><p>When you’re happy everything is working locally, you can apply the migration to production with:</p><pre>npm run db:migrate:prod</pre><p>You can check if it’s worked by finding the corresponding D1 Database in your <a href="https://dash.cloudflare.com/">Cloudflare dashboard</a>.</p><p>There is no easy way to rollback a migration in Cloudflare D1. They use the forward rollback approach, where every rollback is just a further migration.</p><p>However, if you do find yourself in trouble and need to rollback to an earlier state, you can use this method:</p><p><a href="https://developers.cloudflare.com/d1/reference/time-travel/">Time Travel and backups · Cloudflare D1 docs</a></p><h3>Step 4 — Use Drizzle ORM for a Visitor Book</h3><p>Now we will wire everything up. We are going to build a “zero-input” guestbook that logs the user’s location automatically using Cloudflare’s edge data.</p><p>Create a new route:</p><pre>mkdir -p src/routes/visitor<br>touch src/routes/visitor/+page.svelte<br>touch src/routes/visitor/+page.server.ts</pre><h4>Server logic</h4><p>Inside of src/routes/visitor/+page.server.ts paste the following code:</p><pre>import { drizzle } from &#39;drizzle-orm/d1&#39;;<br>import { visitors } from &#39;$lib/server/db/schema&#39;;<br>import { desc } from &#39;drizzle-orm&#39;;<br>import type { PageServerLoad } from &#39;./$types&#39;;<br>import type { Actions } from &#39;@sveltejs/kit&#39;;<br><br>export const load: PageServerLoad = async ({ platform }) =&gt; {<br> const db = drizzle(platform?.env?.DB);<br> // Get the last 10 visitors<br> const list = await db.select().from(visitors).orderBy(desc(visitors.timestamp)).limit(10);<br> return { list };<br>};<br><br>export const actions: Actions = {<br> default: async ({ platform }) =&gt; {<br>  const db = drizzle(platform?.env?.DB);<br><br>  // Cloudflare provides location data automatically via platform.cf<br>  const country = platform?.cf?.country || &#39;Unknown&#39;;<br>  const city = platform?.cf?.city || &#39;Unknown&#39;;<br><br>  await db.insert(visitors).values({<br>   country,<br>   city,<br>   timestamp: new Date()<br>  });<br> }<br>};</pre><p>This connects your D1 database (platform.env.DB) with the request metadata (<a href="https://developers.cloudflare.com/workers/runtime-apis/request/">platform.cf</a>). As you can see, we:</p><ol><li>Import the visitors table from the schema.ts file.</li><li>Set up drizzle with the D1 database binding DB.</li><li>Then insert and select values using the drizzle-orm interface.</li></ol><p>A small aside, to use platform.cf without errors, you’ll need to update your app.d.ts file:</p><pre>import {<br> D1Database,<br> IncomingRequestCfProperties // Add this import<br>} from &#39;@cloudflare/workers-types&#39;;<br><br>// See https://svelte.dev/docs/kit/types#app.d.ts<br>// for information about these interfaces<br>declare global {<br> namespace App {<br>  // interface Error {}<br>  // interface Locals {}<br>  // interface PageData {}<br>  // interface PageState {}<br>  interface Platform {<br>   env: {<br>    DB: D1Database;<br>   };<br>   cf?: IncomingRequestCfProperties; // Add this to the Platform type<br>  }<br> }<br>}<br><br>export {};</pre><h4>The UI</h4><p>Create src/routes/+page.svelte. We use a simple form to trigger the server action.</p><pre>&lt;script&gt;<br> export let data;<br>&lt;/script&gt;<br><br>&lt;div<br> style=&quot;width: 100%; margin: 20px auto;display: flex; flex-direction: column; align-items: center; justify-content: center;&quot;<br>&gt;<br> &lt;h1 style=&quot;font-size: 2rem; margin-bottom: 1rem&quot;&gt;Global Guestbook&lt;/h1&gt;<br> &lt;form method=&quot;POST&quot; style=&quot;margin-bottom: 2rem&quot;&gt;<br>  &lt;button<br>   type=&quot;submit&quot;<br>   style=&quot;padding: 0.5rem 1rem; background: #6366f1; color: white; border: none; border-radius: 0.375rem; cursor: pointer&quot;<br>   &gt;📍 I was here&lt;/button<br>  &gt;<br> &lt;/form&gt;<br> &lt;ul style=&quot;list-style: none; padding: 0&quot;&gt;<br>  {#each data.list as visitor}<br>   &lt;li style=&quot;margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem&quot;&gt;<br>    {#if visitor.country}<br>     &lt;img src=&quot;https://flagcdn.com/24x18/{visitor.country.toLowerCase()}.png&quot; alt=&quot;flag&quot; /&gt;<br>    {/if}<br>    &lt;span&gt;{visitor.city || &#39;Unknown&#39;}{visitor.country ? &#39;, &#39; + visitor.country : &#39;&#39;}&lt;/span&gt;<br>   &lt;/li&gt;<br>  {/each}<br> &lt;/ul&gt;<br>&lt;/div&gt;</pre><h3>Step 5 — Run and Test It</h3><p>Start your local development server:</p><pre>npm run dev</pre><p>Open your browser, and you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOFnaQjC0z9aPLHzlfQQHQ.png" /><figcaption>The appearance of the visitor page on a locally running version.</figcaption></figure><p>Click the button a few times, and you’ll register your location in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW4ZQxOxrnaqPKhiZDAZRw.png" /><figcaption>The appearance of the visitor page on a locally running site after clicking the “I was here” button a number of times.</figcaption></figure><p>There you have it! You have a working application running on a D1 Database with Drizzle ORM.</p><h3>Final Words</h3><p>I hope you enjoyed this quick romp through Drizzle and D1 Databases. With the publication of this article, my series on building a site on Cloudflare is almost complete. All that’s left is product metric tracking with PostHog, stay tuned for that, and happy Drizzlin’!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14ec08e723e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-run-drizzle-orm-on-a-d1-database-in-cloudflare-pages-sveltekit-application-a14ec08e723e">How To Run Drizzle ORM on a D1 Database in Cloudflare Pages SvelteKit Application</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use Firebase Auth in a Cloudflare Pages SvelteKit Application]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-use-firebase-auth-in-a-cloudflare-pages-sveltekit-application-56e10b0b9d77?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/56e10b0b9d77</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[sveltekit]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 20:29:01 GMT</pubDate>
            <atom:updated>2026-08-10T21:33:26.735Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to set up Firebase authentication inside of a SvelteKit application deployed on Cloudflare Pages.</h4><p>In this tutorial, you will learn:</p><ol><li>How to set up a simple Firebase project.</li><li>How to add Firebase to your SvelteKit Application.</li><li>How to hide your SvelteKit application’s features behind Firebase Auth: client-side and server-side.</li><li>How to enable Google and GitHub authentication on that project.</li><li>How to log in users with login buttons and the Firebase web SDK.</li></ol><p>This is the fastest, cheapest way to build a solid authentication system. You get the speed of Cloudflare, coupled with the massive Firebase ecosystem and their fantastic tooling. All free for &lt; 50,000 Monthly Active Users.</p><h3>Prerequisites</h3><p>This tutorial assumes you have the following:</p><ol><li>A Google account to create a Firebase project.</li><li>A SvelteKit web app deployed on Cloudflare Pages.</li><li><a href="https://nodejs.org/en/download">Node.js installed</a> (npm available).</li><li><a href="https://www.npmjs.com/package/firebase-tools">firebase-tools</a> installed globally via npm for CLI access.</li><li><a href="https://tailwindcss.com/docs/installation/using-vite">TailwindCSS</a> installed.</li></ol><p>If you don’t have the second, you can read my initial tutorial on setting one up:</p><p><a href="https://medium.com/full-stack-engineer/the-best-frontend-sveltekit-tailwind-cloudflare-d1778a1a69f5">The Best Frontend — SvelteKit + Tailwind + Cloudflare</a></p><p>Once you have Node installed, you can install firebase-tools with:</p><pre>npm install -g firebase-tools</pre><h3>Step 1 — Log Into Your Firebase Account</h3><p>If you don’t already have one, you can create a Firebase account here:</p><p><a href="https://console.firebase.google.com/u/0/"></a></p><p>Log in with your Google account. Because Google owns Firebase, you’ll immediately be logged in to the console. Congrats! You have yourself a Firebase account.</p><h4>Log in to the CLI</h4><p>We’ll need access to the CLI later in the tutorial, so while we’re in the habit, let’s log in now:</p><pre>firebase login</pre><p>This will load a Google login screen on your browser. Select the account you have associated with Firebase, and click Accept on the permission screens. Bingo, you’re connected to Firebase in your CLI.</p><h3>Step 2 — Create a Firebase Project</h3><p>To use Firebase authentication, we need a Firebase project. The easiest way to set one up is via the Firebase console. Visit the <a href="https://console.firebase.google.com/u/0/">console</a>, and you’ll see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KEgeJION43HF51cl.png" /><figcaption>The Firebase Console Welcome Page.</figcaption></figure><p>Click Get started with a Firebase project. The next screen will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*MyasznI3as_VXyvf2hLhbw.png" /><figcaption>The project name selection screen. (The tiny chip blanked out below my project’s name is the Project’s global ID inside of Google Cloud. It’s an identifier that uniquely links to your project in Google Cloud.)</figcaption></figure><p>From this screen, fill in the name of your project and accept the terms. The name is unimportant; choose what you like. Click Continue and you’ll be asked to sign up for Google Analytics. Decline on this occasion; this is just a simple app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*wjjgP2iIehP4kf6LD13m5Q.png" /><figcaption>The Google Analytics request page.</figcaption></figure><p>Click Create project, and you’ll see a loader like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*zDz4eu_C_4WjCUIFqlMx1g.png" /><figcaption>The Firebase project creation loader.</figcaption></figure><p>Once complete, click through to your project’s page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7a6Ym_Iiy_LFaIahCewig.png" /><figcaption>The Firebase console for the full-stack-gaming-auth project.</figcaption></figure><p>That’s it, your project is set up on Firebase! To check it has worked, go back to your terminal and run the following command:</p><pre>firebase projects:list</pre><p>You should get output like the following:</p><pre>✔ Preparing the list of your Firebase projects<br>┌──────────────────────┬───────────────────────┬────────────────┬──────────────────────┐<br>│ Project Display Name │ Project ID            │ Project Number │ Resource Location ID │<br>├──────────────────────┼───────────────────────┼────────────────┼──────────────────────┤<br>│ hello-world-api      │ hello-world-api-f58de │ 173594737825   │ [Not specified]      │<br>└──────────────────────┴───────────────────────┴────────────────┴──────────────────────┘</pre><p>For security purposes, don’t publicly show people your Project ID or Project Number. It is technically not secret information, but it will still make it easier to find and potentially attack your project. The output above is dummy data, taken from a previously deleted project, unrelated to this one.</p><h3>Step 2 — Add Firebase to Your SvelteKit Application</h3><p>Start by clicking on the web icon in the centre of the homepage of the Firebase console, the &lt;/&gt; symbol, just above Add an app to get started:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7a6Ym_Iiy_LFaIahCewig.png" /><figcaption>The Firebase console for the full-stack-gaming-auth project.</figcaption></figure><p>You’ll see a screen like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*xtOpvu2_9p2Y8PmZv2393g.png" /><figcaption>The Firebase web app registration screen.</figcaption></figure><p>Give your app whatever nickname you like, then click on Register app (it will be blue after you add a nickname). Next, you’ll be shown some instructions and given code to add to your application. The first instruction is to install firebase to npm with:</p><pre>npm install firebase</pre><p>Then you’ll be given some code to add to your application. It will look something like this:</p><pre>// Import the functions you need from the SDKs you need<br>import { initializeApp } from &quot;firebase/app&quot;;<br>// TODO: Add SDKs for Firebase products that you want to use<br>// https://firebase.google.com/docs/web/setup#available-libraries<br><br>const firebaseConfig = {<br>  apiKey: &quot;AIzaSyANqChlsasdfkjj2Kklja2KqNJE&quot;,<br>  authDomain: &quot;&lt;your-app-name&gt;.firebaseapp.com&quot;,<br>  projectId: &quot;&lt;your-app-name&gt;&quot;,<br>  storageBucket: &quot;&lt;your-app-name&gt;.firebasestorage.app&quot;,<br>  messagingSenderId: &quot;3778062234&quot;,<br>  appId: &quot;1:3778062234:web:c413fb692hjks3c01d931e&quot;<br>};<br><br>// Initialize Firebase<br>const app = initializeApp(firebaseConfig);</pre><p>This code is supposed to run on the client side. Yes, even the apiKey. Firebase uses that key to track your project. Hang onto it, we’ll use it in a moment. But first:</p><h4>A Word on Security</h4><p>If it helps, think of it as a projectKey rather than a secret credential, it’s for routing traffic to your backend. If you’re still worried, check out this post:</p><p><a href="https://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public">Is it safe to expose Firebase apiKey to the public?</a></p><p>As your project should only have Firebase Authentication enabled, we don’t even have resources provisioned for an attacker to exploit! If you start using more Firebase services, look into each service&#39;s specific security methods. For example: <a href="https://firebase.google.com/docs/firestore/security/get-started">Firestore rules</a>.</p><h4>Initialise Firebase in Your Application</h4><p>To connect to Firebase in our application, we need to initialise it. To do this properly, we want to initialise it once, in a single location, export it, then reuse it everywhere else.</p><p>Say your SvelteKit application&#39;s src tree looks something like this:</p><pre>📁 src/<br>├── 📄 app.css<br>├── 📄 app.d.ts<br>├── 📄 app.html<br>├── 📄 app_old.css<br>├── 📄 demo.spec.ts<br>├── 📁 lib/<br>│   ├── 📄 index.ts<br>│   ├── 📄 types.ts<br>│   ├── 📁 components/<br>│   │   ├── 📄 Button.svelte<br>│   │   ├── 📄 Card.svelte<br>│   │   ├── 📄 Footer.svelte<br>│   │   ├── 📄 Form.svelte<br>│   │   ├── 📄 FormField.svelte<br>│   │   ├── 📄 Modal.svelte<br>│   │   ├── 📄 Nav.svelte<br>│   │   └── 📄 index.ts<br>│   ├── 📁 data/<br>│   │   └── 📄 games.json<br>├── 📁 routes/<br>│   ├── 📄 +layout.svelte<br>│   ├── 📄 +page.svelte<br>│   ├── 📄 page.svelte.test.ts<br>│   ├── 📁 about/<br>│   │   └── 📄 +page.svelte<br>│   ├── 📁 api/<br>│   │   ├── 📁 comments/<br>│   │   │   └── 📄 +server.ts<br>│   │   ├── 📁 games/<br>│   │   │   ├── 📄 +server.ts<br>│   │   │   ├── 📁 [id]/<br>│   │   │   │   └── 📄 +server.ts<br>│   │   ├── 📁 media/<br>│   │   │   ├── 📁 [...path]/<br>│   │   │   │   └── 📄 +server.ts<br>│   ├── 📁 comments-test/<br>│   │   └── 📄 +page.svelte<br>│   ├── 📁 config/<br>│   │   └── 📄 +page.svelte<br>│   ├── 📁 game/<br>│   │   ├── 📁 [id]/<br>│   │   │   ├── 📄 +page.server.ts<br>│   │   │   └── 📄 +page.svelte<br>│   ├── 📁 image-test/<br>│   │   └── 📄 +page.svelte</pre><p>Create a new directory in src/lib called client. I’ve chosen client to remind me, all the code in this directory should be client-side. Technically, you could call it anything you like, apart from server, which <a href="https://svelte.dev/docs/kit/server-only-modules">SvelteKit forces to be server-side</a>.</p><p>In the new directory, create a file called firebase.svelte.ts.</p><pre>📁 src/<br>├── 📁 lib/<br>│   ├── 📁 client/<br>│   │   ├── 📄 firebase.svelte.ts</pre><p>In this file, paste the following code:</p><pre>import { initializeApp, getApps, type FirebaseApp } from &#39;firebase/app&#39;;<br>import { browser } from &#39;$app/environment&#39;;<br><br>// TODO: Replace with your real configuration!<br>const firebaseConfig = {<br> apiKey: &#39;&lt;your-api-key&gt;&#39;,<br> authDomain: &#39;&lt;your-app-name&gt;.firebaseapp.com&#39;,<br> projectId: &#39;&lt;your-app-name&gt;&#39;,<br> storageBucket: &#39;&lt;your-app-name&gt;.firebasestorage.app&#39;,<br> messagingSenderId: &#39;&lt;your-messaging-sender-id&gt;&#39;,<br> appId: &#39;&lt;your-app-Id&gt;&#39;<br>};<br><br>let firebaseApp: FirebaseApp;<br><br>if (browser) {<br>  // Initialize Firebase<br>  if (!getApps().length) {<br>   firebaseApp = initializeApp(firebaseConfig);<br>  } else {<br>   firebaseApp = getApps()[0];<br>  }<br>}<br><br>// Makes the app available for import in client-side code<br>export { firebaseApp };</pre><p>This initialises your app and exports a client for the rest of your application to import and use. We’ll extend this in <strong>Step 3</strong> to include auth.</p><p>Initialisation is blocked when the browser is undefined to avoid errors being raised by Firebase during SvelteKit’s server-side rendering.</p><h3>Step 3 — The Two Ways To Hide Your Features</h3><p>There are two ways to hide parts of your app behind authentication:</p><ul><li><strong>Client Side</strong>:<br>Use this when you want to give a user gradual access to a page. For example, you’re running a blog, and you’d like the content to be readable by anyone, whilst easy access to the commenting interface is available only to paying users.</li><li><strong>Server Side:</strong><br>Use this when you want the user to have no access at all. For example, a user profile page would never be exposed to an unauthenticated user, because you have no way of knowing who they are.</li></ul><p>Let’s start with the client-side method.</p><h3>Step 4 — Client Side Authentication</h3><p>Within your client/ directory, edit firebase.svelte.ts to add the following:</p><pre>import { initializeApp, getApps, type FirebaseApp } from &#39;firebase/app&#39;;<br>import { getAuth, type Auth } from &#39;firebase/auth&#39;;<br>import { browser } from &#39;$app/environment&#39;;<br><br>// TODO: Replace with your real configuration!<br>const firebaseConfig = {<br> apiKey: &#39;&lt;your-api-key&gt;&#39;,<br> authDomain: &#39;&lt;your-app-name&gt;.firebaseapp.com&#39;,<br> projectId: &#39;&lt;your-app-name&gt;&#39;,<br> storageBucket: &#39;&lt;your-app-name&gt;.firebasestorage.app&#39;,<br> messagingSenderId: &#39;&lt;your-messaging-sender-id&gt;&#39;,<br> appId: &#39;&lt;your-app-Id&gt;&#39;<br>};<br><br>let firebaseApp: FirebaseApp;<br>let firebaseAuth: Auth;<br><br>if (browser) {<br> // Initialize Firebase<br> if (!getApps().length) {<br>  firebaseApp = initializeApp(firebaseConfig);<br> } else {<br>  firebaseApp = getApps()[0];<br> }<br><br> // Initialize Firebase Auth<br> firebaseAuth = getAuth(firebaseApp);<br>}<br><br>export { firebaseApp, firebaseAuth };</pre><p>You can see firebaseAuth is being exported now too, which is what we’ll need to manage authentication.</p><p>Repeating the pattern, we’ll handle auth in a similar centralised location. Create a new file in client/ called auth.svelte.ts:</p><pre>📁 src/<br>├── 📁 lib/<br>│   ├── 📁 client/<br>│   │   ├── 📄 auth.svelte.ts<br>│   │   ├── 📄 firebase.svelte.ts</pre><p>Using .svelte.ts tells SvelteKit to compile the file, so you can use runes like $state. This allows us to manage auth state in a single location. Paste the following into your file:</p><pre>import { firebaseAuth } from &#39;./firebase.svelte&#39;;<br>import { readable } from &#39;svelte/store&#39;;<br>import { onAuthStateChanged, type User } from &#39;firebase/auth&#39;;<br>import { decodeJwt, type JWTPayload } from &#39;jose&#39;;<br>import { browser } from &#39;$app/environment&#39;;<br><br>export interface AuthState {<br> user: User | null;<br> isLoading: boolean;<br>}<br><br>/**<br> * Reactive read-only store for the current user&#39;s authentication state.<br> * This will update when the user&#39;s authentication state changes, and can<br> * be used to trigger rerenders in components that consume the store;<br> */<br>export const currentUserAuthState = readable&lt;AuthState&gt;(<br> {<br>  user: null,<br>  isLoading: true<br> },<br> (set) =&gt; {<br>  // Only run auth state listener in the browser<br>  if (!browser) {<br>   set({ user: null, isLoading: false });<br>   return () =&gt; {};<br>  }<br><br>  const unsubscribe = onAuthStateChanged(firebaseAuth, async (user) =&gt; {<br>   const idToken = await user?.getIdToken();<br><br>   if (!idToken) {<br>    console.log(&#39;onAuthStateChanged::no idToken&#39;);<br><br>    set({ user: null, isLoading: false });<br><br>    return;<br>   }<br><br>   let decodedToken: JWTPayload;<br><br>   try {<br>    decodedToken = await decodeJwt(idToken);<br>   } catch (error) {<br>    console.error(&#39;onAuthStateChanged::error decoding token&#39;, { error, idToken });<br>    <br>    set({ user: null, isLoading: false });<br>    <br>    return;<br>   }<br><br>   console.log(&#39;onAuthStateChanged::decodedToken&#39;, decodedToken);<br><br>   if (user) {<br>    storeTokenInCookie(user);<br>   }<br><br>   set({ user, isLoading: false });<br>  });<br>  return () =&gt; unsubscribe();<br> }<br>);<br><br>// Helper function to store auth token in cookie<br>async function storeTokenInCookie(user: User) {<br> const token = await user.getIdToken();<br> document.cookie = `firebase-token=${token}; path=/; max-age=3600; secure; samesite=strict`;<br>}<br><br>// Get current user<br>export function getCurrentUser(authState: AuthState) {<br> return authState.user;<br>}<br><br>// Check if user is authenticated<br>export function isAuthenticated(authState: AuthState) {<br> return authState.user !== null;<br>}<br><br>// Check if auth is still loading<br>export function isAuthLoading(authState: AuthState) {<br> return authState.isLoading;<br>}<br><br>// Get ID token for API calls<br>export async function getIdToken(authState: AuthState) {<br> if (authState.user) {<br>  return await authState.user.getIdToken();<br> }<br> return null;<br>}</pre><p>Breaking down the above, we have:</p><ul><li><strong>import { firebaseAuth }</strong> — Importing the shared Firebase Authentication instance from the firebase.svelte.ts file.</li><li><strong>currentUserAuthState</strong> — A <a href="https://svelte.dev/docs/svelte/stores#svelte-store-readable">readable store</a> wrapper around the onAuthStateChanged Firebase function. The readable store can be subscribed to in downstream components so that automatic UI updates are triggered.</li><li><strong>onAuthStateChanged</strong> — This is a Firebase auth function that is triggered any time Firebase detects an authentication change in the user. For example, a login, logout, or token invalidation event. When it’s triggered, we’re running a callback to set the user token as a cookie, and then setting the currentUserAuthState store to trigger reactive updates.</li><li><strong>storeTokenInCookie </strong>— This stores the Firebase Auth ID token inside a cookie called firebase-token for up to 1 hour. Meaning the ID token will be passed with every request within that hour. The actual name of the token is entirely up to you, but firebase-token is a good default.</li><li><strong>getCurrentUser</strong> — Returns the currentUser object stored in the central app location. This can be used to retrieve user data and control the UI state.</li><li><strong>isAuthenticated</strong> — Checks if a user exists. Controls conditional rendering of the UI.</li><li><strong>isAuthLoading</strong> — Can be used to block pages from rendering whilst waiting for authentication.</li><li><strong>getIdToken</strong> — Returns the user’s ID token, if they exist. The token can be passed in an API request in the Authorization header, proving the user is who they say they are.</li></ul><h4>Lock Down Some UI</h4><p>Let’s use our auth.svelte.ts API to lock down a page. Set up a basic test route by running the following from src/:</p><pre>cd src<br>mkdir routes/auth-test<br>touch routes/auth-test/+page.svelte</pre><p>Then paste in the following code:</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br> import {<br>  currentUserAuthState,<br>  isAuthenticated,<br>  isAuthLoading,<br>  getIdToken,<br>  type AuthState<br> } from &#39;$lib/client/auth.svelte&#39;;<br> import { onMount } from &#39;svelte&#39;;<br><br> let idToken = $state&lt;string | null&gt;(null);<br> let authState = $state&lt;AuthState | null&gt;(null);<br><br> const unsubscribeAuth = currentUserAuthState.subscribe(async (newAuthState) =&gt; {<br>  idToken = await getIdToken(newAuthState);<br>  authState = newAuthState;<br> });<br><br> onMount(async () =&gt; {<br>  idToken = await getIdToken();<br>  console.log(idToken);<br> });<br><br>  onDestroy(() =&gt; {<br>    unsubscribeAuth();<br>  });<br>&lt;/script&gt;<br><br>{#if isAuthLoading()}<br> &lt;p&gt;Loading...&lt;/p&gt;<br>{:else if isAuthenticated()}<br> &lt;div&gt;<br>  &lt;h1&gt;Auth Test&lt;/h1&gt;<br>  &lt;p&gt;Current User: {getCurrentUser()?.email}&lt;/p&gt;<br>  &lt;p&gt;Is Authenticated: {isAuthenticated()}&lt;/p&gt;<br>  &lt;p&gt;Is Auth Loading: {isAuthLoading()}&lt;/p&gt;<br>  &lt;p&gt;ID Token: {idToken}&lt;/p&gt;<br> &lt;/div&gt;<br>{:else}<br> &lt;div&gt;<br>  &lt;h1&gt;You Suck, Because You&#39;re Not Authenticated&lt;/h1&gt;<br> &lt;/div&gt;<br>{/if}</pre><p>The unsubscribeAuth line is subscribing to the currentUserAuthState and altering state on the frontend to trigger reactive updates. When the page is closed, onDestroy is called. At this point, we unsubscribe from the store to avoid listeners hanging around when they’re no longer required.</p><p>This should give you output similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*b6D9MCuQk1n3BuPg7k3CKw.png" /><figcaption>Full Stack Gaming telling me I’m not authenticated.</figcaption></figure><p>Yours will probably look less interesting, but you should see the same message. This is because no login methods have been set up yet, and you’re not authenticated! More on that later. That’s it for blocking things with auth on the client side; let’s move on to the server side.</p><p>By the way, if you’re curious about the styling, you can read how to create your own here:</p><p><a href="https://medium.com/full-stack-engineer/the-best-frontend-sveltekit-tailwind-cloudflare-d1778a1a69f5">The Best Frontend — SvelteKit + Tailwind + Cloudflare</a></p><h3>Step 5 — Server Side Authentication</h3><p>To authenticate on the server-side, we need to do a bit more work. <a href="https://www.npmjs.com/package/firebase-admin">firebase-admin</a> is the standard tool for server-side authentication, but it relies on Node.js APIs that <a href="https://developers.cloudflare.com/workers/runtime-apis/nodejs/">Cloudflare Workers don’t emulate</a>. So, we have several options:</p><ol><li>Write a simple client that performs the minimum required actions.</li><li>Use a package like <a href="https://github.com/Connor56/cloudfire-auth">cloudfire-auth</a>.</li><li>Use the <a href="https://www.npmjs.com/package/firebase-auth-cloudflare-workers">firebase-auth-cloudflare-workers</a> NPM package.</li></ol><p>My preferred option is to use my own package, Option 2.</p><p>Option 3 is viable, but since both packages achieve the same thing, for brevity, I’ll cover one only.</p><h4>Cloudfire-Auth</h4><p>Install cloudfire-auth with:</p><pre>npm install cloudfire-auth</pre><p>To use cloudfire-auth create a similar directory to the client one and call it server:</p><pre>📁 src/<br>├── 📁 lib/<br>│   ├── 📁 client/<br>│   ├── 📁 server/ </pre><p>Everything within the src/lib/server directory is never sent to the client, this is a <a href="https://svelte.dev/docs/kit/project-structure">SvelteKit Project convention</a>. Within the new directory, add a new file called auth.ts:</p><pre>📁 src/<br>├── 📁 lib/<br>│   ├── 📁 server/<br>│   │   ├── 📄 auth.ts</pre><p>Within this file, add the following code:</p><pre>import { CloudFireAuth } from &#39;cloudfire-auth&#39;;<br>import { base64url } from &#39;jose&#39;;<br><br>import { env } from &#39;$env/dynamic/private&#39;;<br>import type { KVNamespace } from &#39;@cloudflare/workers-types&#39;;<br><br>/**<br> * Create a new CloudFireAuth instance from a service account key you have<br> * stored in your environment variables.<br> * @param kvNamespace KV namespace to use for the auth instance.<br> * @returns CloudFireAuth instance.<br> */<br>export function getServerAuth(kvNamespace: KVNamespace) {<br> const FIREBASE_SERVICE_ACCOUNT_KEY = env.FIREBASE_SERVICE_ACCOUNT_KEY;<br><br> if (!FIREBASE_SERVICE_ACCOUNT_KEY) {<br>  throw new Error(&#39;FIREBASE_SERVICE_ACCOUNT_KEY environment variable is not set&#39;);<br> }<br><br> const decodedKey = base64url.decode(FIREBASE_SERVICE_ACCOUNT_KEY);<br><br> const serviceAccountJsonString = new TextDecoder().decode(decodedKey);<br><br> const serviceAccountKey = JSON.parse(serviceAccountJsonString);<br><br> return new CloudFireAuth(serviceAccountKey, kvNamespace);<br>}</pre><p>Breaking down the above, we have:</p><ul><li><strong>import { env } from &#39;$env/dynamic/private&#39; </strong>— Imports your Firebase service account key secret from CloudFlare’s environment variables on the worker.</li><li><strong>getServerAuth</strong> — This is the core exported function that creates a new instance of CloudFireAuth for interacting with your Firebase project.</li><li><strong>kvNamespace</strong> — This is a <a href="https://developers.cloudflare.com/kv/concepts/kv-namespaces/">KV Namespace</a> you need to attach to your Cloudflare project. It adds caching to your CloudFireAuth instance.</li><li><strong>serviceAccountKey </strong>— The service account key associated with your Firebase project. I store mine as a single base64 variable, hence the decoding. However, as long as the key is passed in as a JavaScript object, it will work correctly.</li><li><strong>CloudFireAuth</strong> — The returned instance that lets you interact with your Firebase Authentication repo.</li></ul><p>It’s safe to put your service account key in an environment variable like: FIREBASE_SERVICE_ACCOUNT_KEY, because any .env variable without a PUBLIC_ prefix is <a href="https://svelte.dev/tutorial/kit/env-static-public">private by default</a>.</p><p>Here’s how you can use your CloudFireAuth to complete the two most common server-side authentication actions.</p><h4>Lock down a Page</h4><p>Imagine you have a feature page for paying users only that you want to lock down. You can do this with the following code in a +page.server.ts file:</p><pre>import { redirect } from &#39;@sveltejs/kit&#39;;<br>import { getServerAuth } from &#39;$lib/server/auth&#39;;<br>import type { PageServerLoad } from &#39;./$types&#39;;<br><br>export const load: PageServerLoad = async ({ cookies, platform }) =&gt; {<br> const token = cookies.get(&#39;firebase-token&#39;);<br><br> if (!token) throw redirect(302, &#39;/auth-test&#39;);<br><br> try {<br>  const cloudfireAuth = await getServerAuth(platform?.env?.KV);<br><br>  // If the token is invalid, an error will be thrown<br>  await cloudfireAuth.verifyIdToken(token);<br><br>  console.log(&#39;token verified&#39;);<br> } catch (error) {<br>  console.error(&#39;Error verifying token:&#39;, error);<br>  throw redirect(302, &#39;/log-in&#39;);<br> }<br>};</pre><p>First, we get an auth instance with getServerAuth, then we run the <a href="https://firebase.google.com/docs/auth/admin/verify-id-tokens">verifyIdToken</a> method on the provided token. If the token verification fails, an error is thrown, triggering a redirect to the login page.</p><p>Put this in front of any page you’d like to lock down to test this.</p><h4>Lock down an API endpoint</h4><p>To use this in an API endpoint, you can add a route like the following:</p><pre>touch src/routes/api/check-auth/+server.ts</pre><p>Paste this into your +server.ts file:</p><pre>import { json } from &#39;@sveltejs/kit&#39;;<br>import type { RequestHandler } from &#39;@sveltejs/kit&#39;;<br>import { getServerAuth } from &#39;$lib/server/auth&#39;;<br><br>export const GET: RequestHandler = async ({ request, platform }) =&gt; {<br> console.log(&#39;request&#39;, request);<br> try {<br>  const cookie = request.headers.get(&#39;cookie&#39;);<br>  const token = cookie?.split(&#39;firebase-token=&#39;)[1];<br><br>  console.log(&#39;token&#39;, token);<br><br>  const serverAuth = getServerAuth(platform?.env?.KV);<br><br>  const idToken = await serverAuth.verifyIdToken(token || &#39;&#39;);<br><br>  console.log(&#39;tokenVerifier&#39;, idToken);<br><br>  return json({ message: &#39;You are authorised&#39; }, { status: 200 });<br> } catch (error) {<br>  console.error(&#39;Error processing request:&#39;, error);<br>  return json({ error: &#39;You are not authorised&#39; }, { status: 401 });<br> }<br>};</pre><p>Similarly, we retrieve an auth instance with getServerAuth. Then we attempt to verify the ID Token from the cookies. If the verification process fails, an error is thrown, and the user receives a JSON response indicating they are not authorised.</p><h4>The KV Namespace</h4><p>In both examples, you can see I’ve used platform?.env?.KV in the getServerAuth function. This is a KV namespace I’ve attached to my project. It caches Google’s public keys for faster token verification.</p><p>To attach a KV Namespace to your project, read this tutorial here:</p><p><a href="https://medium.com/full-stack-engineer/how-to-use-a-kv-namespace-in-a-cloudflare-pages-sveltekit-application-9192db4f7b7e">How To Use a KV Namespace in a Cloudflare Pages SvelteKit Application</a></p><h3>Step 6 — Enable Google and GitHub Authentication</h3><p>The easiest way to handle login is to use one of the default Single Sign-On options in Firebase. Google covers 99% of all use cases, but as my example is for a full-stack gaming site, I’ll use GitHub Auth too.</p><p>To start, switch on Authentication in your Firebase project. Open the Build expansion option in the left sidebar, then click on Get started on the page that opens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*NOBAMtGYJdG3EuWtv263tg.png" /><figcaption>The Firebase console with the Authentication tab selected in the left sidebar.</figcaption></figure><p>On the page that follows, click on the Sign-in method tab and you’ll see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI9KUaqUaeCYdkICKaXQgQ.png" /><figcaption>The Sign-in method selection page on Firebase Authentication.</figcaption></figure><p>The methods for enabling Google and GitHub differ, so I’ll handle them separately.</p><h4>Google</h4><p>Click on the Google provider option in Additional providers. You’ll see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*ijHB2zJUs-QO-jw0wG3FHw.png" /><figcaption>The Google sign-on provider set up screen.</figcaption></figure><p>Click Enable in the top right corner, the Whitelist and Web SDK options can be ignored. You can also ignore the SHA-1 release fingerprint, this is for Android apps only.</p><p>After clicking Enable, you’ll see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*TAiLaJmy6y_Y76CL6qJuzA.png" /><figcaption>The second stage of the Google Sign on setup.</figcaption></figure><p>Complete the options in the following way:</p><ul><li><strong>Public facing name</strong> — Use a pretty name for your website’s URL. For example, mine is <em>Full Stack Gaming</em>.</li><li><strong>Support email</strong> — If you don’t mind using a personal email, the simplest choice is to select the email address that manages the Firebase project. If you’d rather keep it quiet, you can set up a Google Group and use that instead.</li></ul><p>To set up a Google Group, visit this location:</p><p><a href="https://groups.google.com/">https://groups.google.com/</a></p><p>Click on Create group in the top left corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*V8CgHbFUjxEzmKEallc04w.png" /><figcaption>The Create group interface of the google groups page.</figcaption></figure><p>Fill out the details to get a support email.</p><p>Click Next, then choose your visibility preferences, add no members and create your group.</p><p>Close the Configure provider modal, then reload it and re-click to enable Google Sign on. Scroll down to the Support email section, and you will see your Google Group as an email option for support.</p><blockquote>If you want an even prettier email, like support@your-domain.com you’ll need to set it up in a Google Workspace. Comment if you’d like a tutorial on that.</blockquote><p>Inside the Configure provider modal, click on the Save button in the bottom right corner.</p><p>Congratulations! You have enabled Google sign-on, you should see it in your Provider list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtqW1cfPtwt4NRMdOGMCWA.png" /><figcaption>Provider list with the Google Provider enabled.</figcaption></figure><p>I already had Email/Password enabled. You will only see the Google option.</p><h4>GitHub</h4><p>Click on the GitHub option in the Provider list. If you can’t see it click Add new provider. Click Enable and your modal should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KL0jiMYwnNXURjSXCaGotQ.png" /><figcaption>The GitHub Configure provider modal with enabled set to true.</figcaption></figure><p>The red line in the image is covering my Authentication callback URL. Copy this, you’ll need it in a moment. The Client ID and Client secret come from GitHub, and you need to create them by setting up an OAuth app on your account. Visit this URL to start:</p><p><a href="https://github.com/settings/developers">Build software better, together</a></p><p>If you have no apps, you’ll see this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*NIuM9Iljf_cVuJM3VKKTfg.png" /><figcaption>The GitHub OAuth apps page, with no data on it.</figcaption></figure><p>Click on New OAuth app and you’ll be taken to the Register a new OAuth app form. Fill it out with your application’s details, including the callback url copied a moment ago.</p><p>You can leave Enable Device Flow unchecked. Click on Register application and you’ll be taken to a page for your OAuth app.</p><p>Copy your Client ID into the modal on Firebase, mine is covered by the red line. Click on Generate a new client secret.</p><p>Copy this and paste it into the Client secret section of your Configure provider modal on Firebase. You can only copy this secret when it’s newly created. If you mess up, create another and delete the previous one.</p><p>Click Save on the Configure provider modal. Congratulations! You’ve enabled GitHub Authentication on Firebase. You’ll see it on your provider list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpcPS2mhQZP_eUQW7Dx74w.png" /><figcaption>Firebase Sign-in providers list with GitHub enabled.</figcaption></figure><h3>Step 7— Provide the Firebase Auth Sign In Functions</h3><p>Finally, we need the sign-in functions. You can see in the previous step, they are imported from: $lib/client/auth.svelte but they don’t exist yet.</p><p>Add them to your lib/client/auth.svelte file:</p><pre>// .. (Update the firebase/auth imports to this)<br>import {<br> signOut,<br> onAuthStateChanged,<br> signInWithPopup,<br> GoogleAuthProvider,<br> GithubAuthProvider,<br> type User<br>} from &#39;firebase/auth&#39;;<br><br>// Sign in with Google OAuth (popup method)<br>export async function signInWithGoogle() {<br> try {<br>  const provider = new GoogleAuthProvider();<br>  const userCredential = await signInWithPopup(firebaseAuth, provider);<br><br>  await storeTokenInCookie(userCredential.user);<br><br>  return { success: true, user: userCredential.user };<br> } catch (error) {<br>  return { success: false, error: (error as Error).message };<br> }<br>}<br><br>// Sign in with GitHub OAuth (popup method)<br>export async function signInWithGitHub() {<br> try {<br>  const provider = new GithubAuthProvider();<br>  const userCredential = await signInWithPopup(firebaseAuth, provider);<br><br>  await storeTokenInCookie(userCredential.user);<br><br>  return { success: true, user: userCredential.user };<br> } catch (error) {<br>  return { success: false, error: (error as Error).message };<br> }<br>}<br><br>// Sign out<br>export async function logOut() {<br> try {<br>  await signOut(firebaseAuth);<br><br>  // Clear the cookie<br>  document.cookie = &#39;firebase-token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT&#39;;<br><br>  return { success: true };<br> } catch (error) {<br>  return { success: false, error: (error as Error).message };<br> }<br>}</pre><p>These new functions do the following:</p><ul><li><strong>signInWithGoogle</strong> — Uses the GoogleAuthProvider, and signInWithPopup function from Firebase to let the user sign in. If the sign-in completes successfully, the returned token is stored as a cookie.</li><li><strong>signInWithGitHub</strong> — Uses the GithubAuthProvider, and signInWithPopup function from Firebase to let the user sign in. If the sign-in completes successfully, the returned token is stored as a cookie.</li><li><strong>logOut</strong> — Uses the signOut function to log the user out on Firebase, and then delete the token from the cookies.</li></ul><p>The imports in the new version of auth-test will now work correctly. Try logging in, you’ll go through the standard pop-up flow, and when authenticated, you’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3uXGeoyTVucg-2EzHBJhQ.png" /><figcaption>The auth-test page once you’ve successfully logged in.</figcaption></figure><p>I’ve covered up my actual email, but you’ll see yours.</p><h3>Step 8 — Deploy and Test</h3><p>Well, it’s all running locally, so it’s time to deploy and see if it works! Push your changes to GitHub and let the auto-deploy magic happen.</p><p>Login will most likely fail, and you’ll see the following error in the console:</p><pre>Google sign-in error: Firebase: Error (auth/unauthorized-domain).</pre><p>This is because your domain needs to be set as an <em>Authorized Domain</em>. You can do this by going into the <a href="https://console.firebase.google.com/">Firebase console</a>. Going into the auth project we set up earlier, clicking on Authentication in the left-hand side bar, then Settings in the top tab menu.</p><p>Choose Authorized domains in the left-hand panel on the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtSwIhAWMT7LtHBQMpTqQg.png" /><figcaption>The Authorized domains tab in Authentication Settings in the Firebase console.</figcaption></figure><p>Click on Add domain and put in your deployed site’s domain name. Reload your page, and you should now be able to log in as expected! Huzzah!</p><p>Test everything works as expected; if it doesn’t, come back here and leave a comment. I’ll help you!</p><h3>Final Words</h3><p>I hope you enjoyed this particularly long article on setting up Firebase Auth.</p><p>This was a month or two in the making, but it <em>should</em> have beaten a path for anyone to follow. I hope it helps you get set up in an hour, rather than the weeks of struggle I went through. Happy auth’ing!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e10b0b9d77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-use-firebase-auth-in-a-cloudflare-pages-sveltekit-application-56e10b0b9d77">How To Use Firebase Auth in a Cloudflare Pages SvelteKit Application</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use a KV Namespace in a Cloudflare Pages SvelteKit Application]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-use-a-kv-namespace-in-a-cloudflare-pages-sveltekit-application-9192db4f7b7e?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/9192db4f7b7e</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[sveltekit]]></category>
            <category><![CDATA[cloudflare-pages]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 12:10:05 GMT</pubDate>
            <atom:updated>2026-08-10T21:36:21.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to set up a Cloudflare KV Namespace and use it to store and serve data in a SvelteKit application.</h4><p>In this tutorial, you will learn:</p><ol><li>How to set up a KV Namespace via the <a href="https://developers.cloudflare.com/workers/wrangler/">wrangler CLI</a> tool.</li><li>Bind the Namespace to your SvelteKit Cloudflare Pages application.</li><li>Use it in a basic caching service to avoid an external call.</li></ol><p>This is the next article in a series on building a SvelteKit website on Cloudflare.</p><h3>Prerequisites</h3><p>Here’s what you’ll need to complete this tutorial:</p><ul><li>A SvelteKit application deployed to Cloudflare Pages via their GitHub integration.</li><li><a href="https://docs.npmjs.com/cli/v8/commands/npx">npx</a> — The npm eXecutor, it downloads packages and executes commands from them without installing locally.</li><li>Basic knowledge of the <a href="https://nodejs.org/en/learn/getting-started/introduction-to-nodejs">Node.js</a> ecosystem.</li></ul><p>Let’s get started.</p><h3>Step 1 — Set Up The KV Namepsace</h3><p>You can manage your infrastructure from the command line, using Cloudflare’s awesome CLI tool <a href="https://developers.cloudflare.com/workers/wrangler/">wrangler</a>. First, log in to wrangler:</p><pre>npx wrangler login</pre><p>Walk through the OAuth login flow and confirm access for the CLI tool. You can check that you have successfully logged in with:</p><pre>npx wrangler whoami</pre><p>Once you’re successfully logged in, use this command to create your KV Namespace:</p><pre>npx wrangler kv namespace create &lt;your-namespace-name&gt;</pre><p>Add in the name you’d like to give your database. I’m going to use:</p><pre>npx wrangler kv namespace create gaming-kv</pre><p>You’ll see some output like this:</p><pre>{<br>  &quot;kv_namespaces&quot;: [<br>    {<br>      &quot;binding&quot;: &quot;gaming_kv&quot;,<br>      &quot;id&quot;: &quot;9b726c6a1d82347haskb03a7705f01f&quot;<br>    }<br>  ]<br>}</pre><p>Save this, we’ll be using it in the next step. If you want to double-check the database exists, you can run:</p><pre>npx wrangler kv namespace list</pre><p>You’ll get some output like this:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;9b726c6a1d82347haskb03a7705f01f&quot;,<br>    &quot;title&quot;: &quot;gaming-kv&quot;,<br>    &quot;supports_url_encoding&quot;: true<br>  }<br>]</pre><p>Confirming: yes, it worked. You have a KV Namespace. If you’re really worried, you can check in the <a href="https://dash.cloudflare.com/">Cloudflare dashboard</a>.</p><h3>Step 2 — Bind The KV Namespace To Your SvelteKit Application</h3><p>Next, we need to <a href="https://developers.cloudflare.com/pages/functions/bindings/">bind</a> the Namespace, which is the Cloudflare name for adding a resource to your pages application. You do this with a deployment configuration file called: wrangler.jsonc, which defines what resources are attached to your Pages application.</p><p>If you don’t have one already, create one by running the following command from your project’s root:</p><pre>touch wrangler.jsonc</pre><p>Inside this file, paste the following, or something similar:</p><pre>{<br> &quot;name&quot;: &quot;&lt;your-site-name&gt;&quot;,<br> &quot;compatibility_date&quot;: &quot;2025-01-01&quot;,<br> &quot;pages_build_output_dir&quot;: &quot;.svelte-kit/cloudflare&quot;,<br> // &lt;your-output-from-step-1&gt;<br>}</pre><p>In my case, I ended up with the following file:</p><pre>{<br> &quot;name&quot;: &quot;gaming&quot;,<br> &quot;compatibility_date&quot;: &quot;2025-01-01&quot;,<br> &quot;pages_build_output_dir&quot;: &quot;.svelte-kit/cloudflare&quot;,<br> &quot;kv_namespaces&quot;: [<br>    {<br>      &quot;binding&quot;: &quot;gaming_kv&quot;,<br>      &quot;id&quot;: &quot;9b726c6a1d82347haskb03a7705f01f&quot;<br>    }<br>  ]<br>}</pre><p>Here’s an explanation of what all of this means:</p><ul><li>name - The project name used by Wrangler and Cloudflare to identify this app or worker. It’s often used in URLs or dashboard listings.</li><li>compatibility_date - Specifies which version of the Workers runtime APIs your project expects. This allows Cloudflare to avoid breaking changes by locking in behaviour as of this date.</li><li>pages_build_output_dir - The output directory for your built Pages project. In this case, it&#39;s pointing to the SvelteKit build output for Cloudflare. This tells Wrangler to look in this directory for the deployment.</li><li>kv_namespaces - An array of KV Namespace bindings that connect your project to Cloudflare&#39;s KV Namespace service. Each entry in the array represents a Namespace your Worker or Pages project can access.</li><li>binding - The variable name your code will use to reference this KV Namespace (e.g. env.gaming_kv in Workers). You can call this whatever you like. KV is the most commonly used name, but not necessary, as you can see from mine being called gaming_kv. However, it must be a valid TypeScript variable name.</li><li>id - The unique identifier for the KV Namespace instance — required for API operations and deployment linkage.</li></ul><p>With your wrangler.jsonc file set up, push your repo to GitHub and let your site redeploy. Bingo, you can now access a KV Namespace.</p><p>You can double-check this has worked by visiting the <a href="https://dash.cloudflare.com/">Cloudflare dashboard</a>. Going into:</p><p>Compute &amp; AI <strong>→</strong> Workers &amp; Pages <strong>→</strong> &lt;your-site&gt; <strong>→</strong> Settings <strong>→</strong> Bindings</p><p>You can see the KV Namespace is there now.</p><h3>Step 3 — Prepare SvelteKit To Use the KV Namespace</h3><p>Now that the Namespace is connected, we need to set up SvelteKit so that it can use it. You can read more about how to do this in SvelteKit’s <a href="https://svelte.dev/docs/kit/adapter-cloudflare#Cloudflare-Pages">adapter-cloudflare</a> documentation.</p><p>Simply, SvelteKit has a file: <a href="https://svelte.dev/docs/kit/types#app.d.ts">src/app.d.ts</a>. This file defines all of the <em>ambient types</em>. These types are automatically imported and available everywhere in your SvelteKit app. One of those types is: Platform. This type contains platform-specific values. Cloudflare populates this with connections to Cloudflare resources.</p><p>To make the database available, open your src/app.d.ts file:</p><pre>// See https://svelte.dev/docs/kit/types#app.d.ts<br>// for information about these interfaces<br>declare global {<br> namespace App {<br>  // interface Error {}<br>  // interface Locals {}<br>  // interface PageData {}<br>  // interface PageState {}<br>  // interface Platform {}<br> }<br>}<br><br>export {};</pre><p>If you’ve created a brand new SvelteKit site, it will look like the above. You have:</p><ul><li>global — A declaration, which allows you to extend the global variable space.</li><li>namespace App— A namespace within the global space that helps you avoid aliasing.</li></ul><p>Within the namespace, you can see all of the standard SvelteKit type interfaces commented out. We want to uncomment the Platform interface and tell SvelteKit to expect a KV Namespace:</p><pre>import { KVNamespace } from &#39;@cloudflare/workers-types&#39;;<br><br>// See https://svelte.dev/docs/kit/types#app.d.ts<br>// for information about these interfaces<br>declare global {<br> namespace App {<br>  // interface Error {}<br>  // interface Locals {}<br>  // interface PageData {}<br>  // interface PageState {}<br>  interface Platform {<br>   env: {<br>    gaming_kv: KVNamespace;<br>   };<br>  }<br> }<br>}<br><br>export {};</pre><p>The resulting code should look like the above. This makes your Namespace available under platorm.env.&lt;your-name-here&gt;. In my case, platform.env.gaming_kv.</p><p>If you’re seeing an error on the KVNamespace top-level import, you may need to install the @cloudflare/workers-types. You can do this with:</p><pre>npm install @cloudflare/workers-types</pre><p>That’s it, you can now use your KV Namespace with:</p><pre>platform.env.gaming_kv</pre><p>In your server-side worker code.</p><h3>Step 4 — Build a Weather Caching Service</h3><p>As an example of a possible use case, we’ll build a weather caching service. For the sake of this tutorial, let’s:</p><ol><li>Get the weather forecast for London via an API.</li><li>Cache it in our KV Namespace for 1 hour.</li><li>Return the cached value to users.</li></ol><p>To do this, you’ll need to make two new files. One for an API route:</p><pre>mkdir -p routes/api/weather<br>touch routes/api/weather/+server.ts</pre><p>Then one for a new page:</p><pre>mkdir -p routes/weather-test<br>touch routes/weather-test/+page.svelte</pre><p>We’ll deal with these one at a time.</p><h4>API route setup</h4><p>Add the following code to your +server.ts:</p><pre>import { json } from &#39;@sveltejs/kit&#39;;<br>import type { RequestHandler } from &#39;./$types&#39;;<br><br>interface WeatherResponse {<br> temperature: string;<br> condition: string;<br> location: string;<br> cached: boolean;<br> duration: number;<br> timestamp: number;<br>}<br><br>interface CachedData {<br> temperature: string;<br> condition: string;<br> timestamp: number;<br>}<br><br>const CACHE_KEY = &#39;weather:london&#39;;<br>const CACHE_TTL = 3600;<br><br>async function fetchWeatherFromAPI(): Promise&lt;{ temperature: string; condition: string }&gt; {<br> const response = await fetch(&#39;https://wttr.in/London?format=j1&#39;);<br> <br> if (!response.ok) {<br>  throw new Error(&#39;Failed to fetch weather data&#39;);<br> }<br> <br> const data = await response.json();<br> <br> const current = data.current_condition[0];<br> <br> return {<br>  temperature: current.temp_C,<br>  condition: current.weatherDesc[0].value<br> };<br>}<br><br>export const GET: RequestHandler = async ({ platform }) =&gt; {<br> const startTime = Date.now();<br><br> if (!platform?.env?.KV) {<br>  return json({ error: &#39;KV namespace not available&#39; }, { status: 500 });<br> }<br><br> const kv = platform.env.KV;<br><br> try {<br>  const cachedData = (await kv.get(CACHE_KEY, { type: &#39;json&#39; })) as CachedData;<br><br>  if (cachedData) {<br>   const duration = Date.now() - startTime;<br>   <br>   return json({<br>    temperature: cachedData.temperature,<br>    condition: cachedData.condition,<br>    location: &#39;London&#39;,<br>    cached: true,<br>    duration,<br>    timestamp: cachedData.timestamp<br>   } as WeatherResponse);<br>  }<br><br>  const weatherData = await fetchWeatherFromAPI();<br>  const timestamp = Date.now();<br><br>  await kv.put(CACHE_KEY, JSON.stringify({ ...weatherData, timestamp }), {<br>   expirationTtl: CACHE_TTL<br>  });<br><br>  const duration = Date.now() - startTime;<br><br>  return json({<br>   ...weatherData,<br>   location: &#39;London&#39;,<br>   cached: false,<br>   duration,<br>   timestamp<br>  } as WeatherResponse);<br> } catch (error) {<br>  console.error(&#39;Error fetching weather:&#39;, error);<br>  <br>  return json(<br>   {<br>    error: &#39;Failed to fetch weather data&#39;,<br>    message: error instanceof Error ? error.message : &#39;Unknown error&#39;<br>   },<br>   { status: 500 }<br>  );<br> }<br>};<br><br>export const DELETE: RequestHandler = async ({ platform }) =&gt; {<br> if (!platform?.env?.KV) {<br>  return json({ error: &#39;KV namespace not available&#39; }, { status: 500 });<br> }<br><br> const kv = platform.env.KV;<br><br> try {<br>  await kv.delete(CACHE_KEY);<br>  <br>  return json({ success: true, message: &#39;Cache cleared&#39; });<br> } catch (error) {<br>  console.error(&#39;Error clearing cache:&#39;, error);<br>  <br>  return json(<br>   {<br>    error: &#39;Failed to clear cache&#39;,<br>    message: error instanceof Error ? error.message : &#39;Unknown error&#39;<br>   },<br>   { status: 500 }<br>  );<br> }<br>};</pre><p>Within this code, you’ll see locations where I’m using platform.env.KV. You need to replace this with the actual name of your KV Namespace, as defined in app.d.ts in <strong>Step 3</strong>.</p><p>Breaking the code down, we have the following endpoints:</p><ol><li>The GET request endpoint that either retrieves the weather forecast from the <a href="https://github.com/chubin/wttr.in">wttr.in</a> API endpoint. Or, if the weather is cached, returns the cached value instead.</li><li>The DELETE request endpoint that clears the weather forecast held in the KV Namespace.</li></ol><p>If you don’t understand endpoints like this, you can read about them here:</p><p><a href="https://medium.com/full-stack-engineer/sveltekit-cloudflare-create-an-api-endpoint-431ec920fd5d">SvelteKit + Cloudflare — Create an API Endpoint</a></p><h4>Weather page setup</h4><p>To set up the frontend, paste the following into your +page.svelte:</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br> import { Button } from &#39;$lib/components&#39;;<br><br> interface WeatherData {<br>  temperature: string;<br>  condition: string;<br>  location: string;<br>  cached: boolean;<br>  duration: number;<br>  timestamp: number;<br> }<br><br> let weatherData = $state&lt;WeatherData | null&gt;(null);<br> let loading = $state(false);<br> let clearingCache = $state(false);<br> let error = $state&lt;string | null&gt;(null);<br> let clientStartTime = $state(0);<br><br> async function fetchWeather() {<br>  loading = true;<br>  error = null;<br>  weatherData = null;<br>  clientStartTime = Date.now();<br><br>  try {<br>   const response = await fetch(&#39;/api/weather&#39;);<br>   <br>   if (!response.ok) {<br>    const errorData = await response.json();<br>    throw new Error(errorData.error || &#39;Failed to fetch weather&#39;);<br>   }<br>   <br>   weatherData = await response.json();<br>  } catch (err) {<br>   error = err instanceof Error ? err.message : &#39;Unknown error occurred&#39;;<br>  } finally {<br>   loading = false;<br>  }<br> }<br><br> async function clearCache() {<br>  clearingCache = true;<br>  error = null;<br><br>  try {<br>   const response = await fetch(&#39;/api/weather&#39;, { method: &#39;DELETE&#39; });<br>   <br>   if (!response.ok) {<br>    const errorData = await response.json();<br>    throw new Error(errorData.error || &#39;Failed to clear cache&#39;);<br>   }<br>   <br>   weatherData = null;<br>  } catch (err) {<br>   error = err instanceof Error ? err.message : &#39;Unknown error occurred&#39;;<br>  } finally {<br>   clearingCache = false;<br>  }<br> }<br><br> function formatDuration(ms: number): string {<br>  if (ms &lt; 1000) {<br>   return `${ms}ms`;<br>  }<br>  return `${(ms / 1000).toFixed(2)}s`;<br> }<br><br> function formatTimestamp(timestamp: number): string {<br>  return new Date(timestamp).toLocaleTimeString();<br> }<br>&lt;/script&gt;<br><br>&lt;div class=&quot;container&quot;&gt;<br> &lt;h1&gt;Weather Cache Test&lt;/h1&gt;<br><br> &lt;div class=&quot;buttons&quot;&gt;<br>  &lt;Button onclick={fetchWeather} disabled={loading}&gt;<br>   {loading ? &#39;Fetching...&#39; : &#39;Fetch Weather&#39;}<br>  &lt;/Button&gt;<br>  &lt;Button onclick={clearCache} disabled={clearingCache} variant=&quot;outline&quot;&gt;<br>   {clearingCache ? &#39;Clearing...&#39; : &#39;Clear Cache&#39;}<br>  &lt;/Button&gt;<br> &lt;/div&gt;<br><br> {#if error}<br>  &lt;div class=&quot;error&quot;&gt;<br>   {error}<br>  &lt;/div&gt;<br> {/if}<br><br> {#if weatherData}<br>  &lt;div class=&quot;weather-card&quot;&gt;<br>   &lt;div class=&quot;weather-main&quot;&gt;<br>    &lt;h2&gt;London&lt;/h2&gt;<br>    &lt;div class=&quot;temperature&quot;&gt;{weatherData.temperature}°C&lt;/div&gt;<br>    &lt;div class=&quot;condition&quot;&gt;{weatherData.condition}&lt;/div&gt;<br>   &lt;/div&gt;<br><br>   &lt;div class=&quot;weather-details&quot;&gt;<br>    &lt;div class=&quot;detail-row&quot;&gt;<br>     &lt;span&gt;Source:&lt;/span&gt;<br>     &lt;span class={weatherData.cached ? &#39;cached&#39; : &#39;external&#39;}&gt;<br>      {weatherData.cached ? &#39;Cache&#39; : &#39;External API&#39;}<br>     &lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;detail-row&quot;&gt;<br>     &lt;span&gt;Server Duration:&lt;/span&gt;<br>     &lt;span&gt;{formatDuration(weatherData.duration)}&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;detail-row&quot;&gt;<br>     &lt;span&gt;Client Duration:&lt;/span&gt;<br>     &lt;span&gt;{formatDuration(Date.now() - clientStartTime)}&lt;/span&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;detail-row&quot;&gt;<br>     &lt;span&gt;Timestamp:&lt;/span&gt;<br>     &lt;span&gt;{formatTimestamp(weatherData.timestamp)}&lt;/span&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> {/if}<br><br> &lt;div class=&quot;info&quot;&gt;<br>  &lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;<br>  &lt;ul&gt;<br>   &lt;li&gt;First request fetches from external API and caches for 1 hour&lt;/li&gt;<br>   &lt;li&gt;Subsequent requests within 1 hour return cached data (faster)&lt;/li&gt;<br>   &lt;li&gt;After 1 hour, cache expires and next request fetches fresh data&lt;/li&gt;<br>  &lt;/ul&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;style&gt;<br> .container {<br>  max-width: 600px;<br>  margin: 0 auto;<br>  padding: 2rem 1rem;<br> }<br><br> h1 {<br>  font-size: 1.5rem;<br>  font-weight: bold;<br>  margin-bottom: 1.5rem;<br> }<br><br> .buttons {<br>  display: flex;<br>  gap: 0.75rem;<br>  margin-bottom: 1.5rem;<br> }<br><br> .error {<br>  background-color: #fee;<br>  border: 1px solid #f44;<br>  color: #c00;<br>  padding: 0.75rem 1rem;<br>  border-radius: 4px;<br>  margin-bottom: 1rem;<br> }<br><br> .weather-card {<br>  background: white;<br>  border: 1px solid #ccc;<br>  border-radius: 4px;<br>  padding: 1.5rem;<br>  margin-bottom: 1.5rem;<br> }<br><br> .weather-main {<br>  margin-bottom: 1rem;<br> }<br><br> .weather-main h2 {<br>  font-size: 1.25rem;<br>  font-weight: 600;<br>  margin-bottom: 0.5rem;<br> }<br><br> .temperature {<br>  font-size: 2rem;<br>  font-weight: bold;<br>  color: black;<br>  margin-bottom: 0.25rem;<br> }<br><br> .condition {<br>  font-size: 1rem;<br>  color: #555;<br> }<br><br> .weather-details {<br>  border-top: 1px solid #ddd;<br>  padding-top: 1rem;<br> }<br><br> .detail-row {<br>  display: flex;<br>  justify-content: space-between;<br>  margin-bottom: 0.5rem;<br> }<br><br> .detail-row span:first-child {<br>  font-weight: 500;<br>  color: #000;<br> }<br><br> .detail-row span:last-child {<br>  color: #000;<br> }<br><br> .cached {<br>  color: #059669;<br>  font-weight: 500;<br> }<br><br> .external {<br>  color: #ea580c;<br>  font-weight: 500;<br> }<br><br> .info {<br>  font-size: 0.875rem;<br>  color: #666;<br> }<br><br> .info p {<br>  margin-bottom: 0.5rem;<br> }<br><br> .info ul {<br>  list-style: disc;<br>  list-style-position: inside;<br> }<br><br> .info li {<br>  margin-bottom: 0.25rem;<br> }<br>&lt;/style&gt;</pre><p>Apologies for the large chunk of code, but it does make for a very pretty frontend. To see it working run your development server with:</p><pre>npm run dev</pre><p>Navigate to /weather-test and you’ll see something similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8Z4CgeWJnjfbkiIKXij2w.png" /><figcaption>The frontend UI with buttons to click for fetching the weather and clearing the cache.</figcaption></figure><h4>The results</h4><p>Click the Fetch Weather button and after a short wait you’ll see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHeyYoM0ll27itPgI0_xUA.png" /><figcaption>The speed of the weather forecast fetch when using the wttr.in API call.</figcaption></figure><p>As you can see, the initial call took 3.68 seconds. Hit the Fetch Weather button again and you’ll see the power of the cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhED-6vP3a2mptN6skTz8w.png" /><figcaption>The speed of the weather forecast fetch when using the Cached data.</figcaption></figure><p>As you can see, it’s now down to 15ms. About <strong>240</strong> <strong>times faster</strong>. This varies somewhat, and as we’re running locally, there will definitely be a speedup from that too, but you should expect total client durations of around 50ms. About <strong>72 times faster</strong>.</p><p>This is the difference between a lightning-fast user experience and a sluggish, irritating experience.</p><h3>Final Words</h3><p>Congratulations, you can now include a KV Namespace in your Cloudflare SvelteKit application!</p><p>I hope this tutorial has helped you integrate KV Namespace into your project and get your next great idea out the door! Happy namespacing 😁</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9192db4f7b7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-use-a-kv-namespace-in-a-cloudflare-pages-sveltekit-application-9192db4f7b7e">How To Use a KV Namespace in a Cloudflare Pages SvelteKit Application</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build a Svelte 5 Component NPM Package]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-build-a-svelte-5-component-npm-package-abcd89bfa9e7?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/abcd89bfa9e7</guid>
            <category><![CDATA[sveltekit]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 20:34:24 GMT</pubDate>
            <atom:updated>2026-08-10T21:02:03.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to create reusable Svelte 5 components and release them on NPM.</h4><p>In this tutorial, you will learn:</p><ol><li>How to use <a href="https://svelte.dev/docs/cli/sv-create">sv create</a> to scaffold your package.</li><li>How to add a component.</li><li>How to package and publish to NPM.</li></ol><p>The path to publishing is simple thanks to the brilliant work of the Svelte team:</p><p><a href="https://svelte.dev/docs/kit/packaging">Packaging</a></p><h3>Prerequisites</h3><p>This tutorial assumes you have the following:</p><ol><li>A Node package manager, <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">npm</a> or <a href="https://pnpm.io/installation">pnpm</a> are most common.</li><li>An <a href="https://www.npmjs.com/signup">account on NPM</a>.</li><li>Some <a href="https://www.theapplegeek.co.uk/blog/basicterminal">terminal knowledge</a>.</li></ol><p>As long as you have these, you’re good to go.</p><h3>Step 1 — Scaffold the Package</h3><p>To scaffold your package, open a terminal. Navigate to the location where you want to store your package, then create a new directory named after your package. Here’s my example below:</p><pre>mkdir svelte-social-login-buttons</pre><p>cd into the directory, and then run the following:</p><pre>npx sv create</pre><p>This will start a terminal process that guides you through a multiple-choice list. The list defines your project structure and looks like this:</p><pre>&gt; npx sv create<br><br>┌  Welcome to the Svelte CLI! (v0.11.2)<br>│<br>◇  Where would you like your project to be created?<br>│  ./<br>│<br>◇  Directory not empty. Continue?<br>│  Yes<br>│<br>◇  Which template would you like?<br>│  Svelte library<br>│<br>◇  Add type checking with TypeScript?<br>│  Yes, using TypeScript syntax<br>│<br>◇  What would you like to add to your project? (use arrow keys / space bar)<br>│  prettier<br>│<br>◆  Project created<br>│<br>◆  Successfully setup add-ons: prettier<br>│<br>◇  Which package manager do you want to install dependencies with?<br>│<br>│  pnpm dlx sv create --template library --types ts --add prettier --install pnpm ./<br>│<br>◆  Successfully installed dependencies with pnpm<br>│<br>◇  What&#39;s next? ───────────────────────────────╮<br>│                                              │<br>│  📁 Project steps                            │<br>│                                              │<br>│    1: pnpm run dev --open                    │<br>│                                              │<br>│  To close the dev server, hit Ctrl-C         │<br>│                                              │<br>│  Stuck? Visit us at https://svelte.dev/chat  │<br>│                                              │<br>├──────────────────────────────────────────────╯<br>│<br>└  You&#39;re all set!</pre><p>Each question has a diamond outline on the left-hand side. The answer you should give is below. For example:</p><ul><li><strong>Question:</strong> Which template would you like?<br><strong>Answer:</strong> Svelte library</li></ul><p>When asked what you would like to add to your project, choose whatever group of tools you like. I selected prettier as my component library is simple.</p><p>When you complete this process, you will have the following folder structure (or something similar):</p><pre>📁 ./<br>├── 📄 .gitignore<br>├── 📄 .npmrc<br>├── 📄 .prettierignore<br>├── 📄 .prettierrc<br>├── 📄 README.md<br>├── 📄 package.json<br>├── 📄 svelte.config.js<br>├── 📄 tsconfig.json<br>├── 📄 vite.config.ts<br>├── 📁 src/<br>│   ├── 📄 app.d.ts<br>│   ├── 📄 app.html<br>│   ├── 📁 lib/<br>│   │   └── 📄 index.ts<br>│   ├── 📁 routes/<br>│   │   └── 📄 +page.svelte<br>├── 📁 static/<br>│   └── 📄 favicon.svg</pre><p>If you check inside the package.json you’ll see the name of the package is the name of the folder you created it in. Install all of the default dependencies with your package manager:</p><pre>npm install<br>// or<br>pnpm install</pre><p>Add git source control with:</p><pre>git init</pre><p>Update your README.md, to explain the purpose of your package and how to use it.</p><h4>A structural aside</h4><p>If you’ve built SvelteKit sites before, you’ll notice a similarity. This is deliberate. Although I can’t find explicit documentation on why the structure is the way it is, I believe this is the reasoning:</p><ol><li>In order to produce good Svelte components, you need the Svelte and SvelteKit backend to process them.</li><li>SvelteKit already has a well-designed project structure that the tooling expects and is set up to deal with.</li><li>Therefore, to reduce tooling friction, the Svelte team adopted a similar project structure for producing Svelte libraries as NPM packages.</li><li>Because NPM packages often have documentation websites, they left the /routes directory in place and gave you an easy way to release a docs site and test your components.</li></ol><p>If someone more in the know than I can confirm this, I would be very grateful.</p><h3>Step 2 — Add a Component</h3><p>To add components to your package, use the /src/lib directory, and export them from the index.ts file. So your /lib directory looks like this:</p><pre>📁 lib/<br>├── 📄 AComponent.svelte<br>└── 📄 index.ts</pre><p>and your index.ts file looks like this:</p><pre>export { default as AComponent } from &#39;./AComponent.svelte&#39;;</pre><h3>Step 3 — Build the Package</h3><p>To create the NPM package, run the following:</p><pre>npm pack</pre><p>This will generate a /dist folder that can be published on NPM with all the appropriate types and Svelte 5 components.</p><h4>What happens under the hood?</h4><p>Look inside the package.json file in the root, you can see what this triggers:</p><pre>{<br> &quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;vite dev&quot;,<br>  &quot;build&quot;: &quot;vite build &amp;&amp; npm run prepack&quot;,<br>  &quot;preview&quot;: &quot;vite preview&quot;,<br>  &quot;prepare&quot;: &quot;svelte-kit sync || echo &#39;&#39;&quot;,<br>  &quot;prepack&quot;: &quot;svelte-kit sync &amp;&amp; svelte-package &amp;&amp; publint&quot;,<br>  &quot;check&quot;: &quot;svelte-kit sync &amp;&amp; svelte-check --tsconfig ./tsconfig.json&quot;,<br>  &quot;check:watch&quot;: &quot;svelte-kit sync &amp;&amp; svelte-check --tsconfig ./tsconfig.json --watch&quot;,<br>  &quot;format&quot;: &quot;prettier --write .&quot;,<br>  &quot;lint&quot;: &quot;prettier --check .&quot;<br> }<br>}</pre><p>npm pack runs both prepare and prepack, but let’s focus on prepack as it does prepare’s job too. We have:</p><ul><li><strong>svelte-kit sync</strong> — This <a href="https://stackoverflow.com/questions/77843430/what-does-svelte-kit-sync-do">autogenerates types</a> and creates the tsconfig.json for your project.</li><li><strong>svelte-package</strong> — This is the packaging step; it creates .js and .d.ts files from your .svelte components.</li><li><strong>publint</strong> — A package linter that <a href="https://publint.dev/docs/">ensures maximum compatibility</a> across environments.</li></ul><p>Together, these generate the correct setup and packaged files for publication to NPM.</p><h3>Step 4 — Publish to NPM</h3><p>You can publish your /dist directory to NPM with:</p><pre>npm publish</pre><p>This will deploy your package to your NPM account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGfEaSDi4Z5_LXdQo3uauQ.png" /><figcaption>What my Svelte 5 components look like on the web.</figcaption></figure><p>Congratulations! You have successfully released a Svelte 5 component package.</p><h3>Final Words</h3><p>I hope this helps you release components quickly and gets you using custom-built UI for all of your projects! Happy componenting.</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abcd89bfa9e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-build-a-svelte-5-component-npm-package-abcd89bfa9e7">How To Build a Svelte 5 Component NPM Package</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Shrink the File Size of a Screen Recording on Mac]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-shrink-the-file-size-of-a-screen-recording-on-mac-7b220339df63?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/7b220339df63</guid>
            <category><![CDATA[quicktime]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[video-production]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 10:48:55 GMT</pubDate>
            <atom:updated>2026-01-12T14:41:40.893Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to take your QuickTime screen recording and reduce its file size by up to 10x!</h4><p>In this tutorial, you will learn how to reduce the file size of your <a href="https://en.wikipedia.org/wiki/QuickTime">QuickTime</a> Movie using ffmpeg. This process can reduce file sizes by up to 10x, making them sendable in emails or postable on GitHub PRs on the free account.</p><h3>Step 1 — Install ffmpeg</h3><p>To get started, you need the following:</p><ul><li>ffmpeg — an open-source image and multimedia processing framework.</li></ul><p>To get it, you can either install it from its website:</p><p><a href="https://www.ffmpeg.org/download.html">Download FFmpeg</a></p><p>Or, my preferred option, you can download it with homebrew. Homebrew is a package manager for macOS. You can download it here if you don’t have it already:</p><p><a href="https://brew.sh/">Homebrew</a></p><p>Once you have homebrew installed, you can run the following:</p><pre>brew install ffmpeg</pre><p>This will install the following Homebrew formula:</p><p><a href="https://formulae.brew.sh/formula/ffmpeg">ffmpeg</a></p><p>Whatever you choose, get ffmpeg installed and move on to the second step.</p><h3>Step 2 — Shrink Your File!</h3><p>With ffmpeg installed, crack open a terminal. To do so, open Launchpad and type terminal in the top search bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1V_GVnJBv7FragCRgEM8xw.png" /><figcaption>My launchpad with the Terminal application showing.</figcaption></figure><p>Click on that, and you’ll have a terminal loaded. To shrink the video size type this command into the terminal:</p><pre>ffmpeg -i &lt;path-to-your-quick-time-movie&gt;.mov -vcodec libx264 -crf 23 \<br>-preset slow -vf &quot;scale=-2:1080&quot; &lt;your-new-path-and-file-name&gt;.mp4</pre><p>Fill in these fields:</p><ul><li>&lt;path-to-your-quick-time-movie&gt; (it should end in .mov)</li><li>&lt;your-new-path-and-file-name&gt; (it will be a .mp4 file)</li></ul><p>If you don’t understand how paths work in the terminal, read this:</p><p><a href="https://www.theapplegeek.co.uk/blog/basicterminal">Beginner&#39;s Guide to macOS and Linux Terminal Commands - The Apple Geek</a></p><p>The other options in the command are:</p><ul><li>-vcodec libx264 — This is the name of a <a href="https://en.wikipedia.org/wiki/Video_codec">video codec</a>, the software we’re going to use to recompress the video.</li><li>-crf 23 — This stands for the <strong><em>constant rate factor</em></strong>, which controls the quality of the video. The range is from 0 (lossless) to 51 (very lossy). Typical values range from 18 for decent quality to 28 for lossy but acceptable quality. I’ve chosen 23 as a happy medium.</li><li>-preset slow — Controls how much time ffmpeg spends trying to produce an efficient compression. The slow value requires more CPU time but will result in a smaller file size. fast speeds up compression but produces larger file sizes.</li><li>-vf &quot;scale=-2:1080&quot; — Applies a <strong><em>video filter</em></strong> that resizes the video. The height is set to 1080 pixels, and the width is automatically calculated to preserve the original aspect ratio. The `-2` ensures the computed width is divisible by 2, which is required by many video codecs.</li></ul><p>Run the command above, and you will see output like the following:</p><pre>frame=4961 fps=393 q=31.0 size=3072KiB time=00:01:22.65 bitrate=304.5kbits/s speed=6.55x elapsed=0:00:12.61 </pre><p>This is recompressing your video! If your video is under 5 minutes in size, this will take less than a minute. You can see the actual speedup given above as speed=6.55x, in other words, the video is compressing 6.55 seconds of video every second.</p><p>The result, a 10x size decrease for a small quality drop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kOcRITB_SKxUMo3aVUPAQ.png" /><figcaption>My original screen recording and my small screen recording, showing a 10x file size decrease.</figcaption></figure><h3>Extras — As a Shell Script</h3><p>If you understand how to manage your Terminal’s shell in macOS, then you can add the following shell script to your source file:</p><pre># Used to shrink the size of QuickTime recording<br># (optionally deletes the original file with -delete or --d flag)<br>function shrink-vid() {<br>    # Parse arguments for delete flag<br>    delete_original=false<br>    input_file_path=&quot;&quot;<br>    output_file_path=&quot;&quot;<br>    <br>    for arg in &quot;$@&quot;; do<br>        if [ &quot;$arg&quot; = &quot;-delete&quot; ] || [ &quot;$arg&quot; = &quot;--d&quot; ]; then<br>            delete_original=true<br>        elif [ -z &quot;$input_file_path&quot; ]; then<br>            input_file_path=$arg<br>        elif [ -z &quot;$output_file_path&quot; ]; then<br>            output_file_path=$arg<br>        fi<br>    done<br><br>    # Check if the input file path is provided<br>    if [ -z &quot;$input_file_path&quot; ]; then<br>        echo &quot;Input file path is required&quot;<br>        return 1<br>    fi<br><br>    # Check if the input file path exists<br>    if [ ! -f &quot;$input_file_path&quot; ]; then<br>        echo &quot;Input file path does not exist&quot;<br>        return 1<br>    fi<br><br>    if [ -z &quot;$output_file_path&quot; ]; then<br>        echo &quot;Output file path not provided, using input file path as output file path&quot;<br>        output_file_path=$input_file_path<br>        output_file_path=${output_file_path%.*}<br>        output_file_path=${output_file_path}.mp4<br>    fi<br><br>    # Initial output<br>    echo &quot;Input file path: $input_file_path&quot;<br>    echo &quot;Output file path: $output_file_path&quot;<br>    if [ &quot;$delete_original&quot; = true ]; then<br>        echo &quot;Original file will be deleted after compression&quot;<br>    else<br>        echo &quot;Original file will be kept after compression&quot;<br>    fi<br><br>    # Shrink the recording, uses mid-level compression and keeps video at 1080p quality.<br>    # Compresses to mp4 format with libx264 codec.<br>    ffmpeg -i &quot;$input_file_path&quot; -vcodec libx264 -crf 23 -preset slow -vf &quot;scale=-2:1080&quot; &quot;$output_file_path&quot;<br><br>    # Print sizes before and after, and compression ratio<br>    if [ -f &quot;$input_file_path&quot; ] &amp;&amp; [ -f &quot;$output_file_path&quot; ]; then<br>        original_size=$(stat -f%z &quot;$input_file_path&quot; 2&gt;/dev/null || stat -c%s &quot;$input_file_path&quot;)<br>        new_size=$(stat -f%z &quot;$output_file_path&quot; 2&gt;/dev/null || stat -c%s &quot;$output_file_path&quot;)<br><br>        # Convert sizes to MB with 2 decimals<br>        original_mb=$(awk &quot;BEGIN {printf \&quot;%.2f\&quot;, $original_size/1024/1024}&quot;)<br>        new_mb=$(awk &quot;BEGIN {printf \&quot;%.2f\&quot;, $new_size/1024/1024}&quot;)<br>        if [ &quot;$original_size&quot; -ne 0 ]; then<br>            ratio=$(awk &quot;BEGIN {printf \&quot;%.2f\&quot;, $original_size/$new_size}&quot;)<br>        else<br>            ratio=&quot;N/A&quot;<br>        fi<br><br>        echo &quot;Original size: $original_mb MB&quot;<br>        echo &quot;New size: $new_mb MB&quot;<br>        echo &quot;Compression ratio: $ratio&quot;<br>    fi<br>    <br>    # Delete the original file<br>    if [ &quot;$delete_original&quot; = true ]; then<br>        rm &quot;$input_file_path&quot;<br>    fi<br>}</pre><p>This can be used like this:</p><pre>shrink-vid &quot;input/file/path.mov&quot; &quot;output/file/path.mp4&quot; --d</pre><p>Add the --d flag if you want to delete the input video. If you don’t provide an output file path, the input file path will be used and overwritten.</p><h3>Final Words</h3><p>That’s it! I hope this helps you send videos to friends and colleagues in emails, and keeps you posting UI walkthroughs on GitHub PRs. Happy compressing!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b220339df63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-shrink-the-file-size-of-a-screen-recording-on-mac-7b220339df63">How To Shrink the File Size of a Screen Recording on Mac</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Limit CollectionGroup Queries to a Particular Path]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-limit-collectiongroup-queries-to-a-particular-path-ba8e32ed0cc0?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba8e32ed0cc0</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 19:17:25 GMT</pubDate>
            <atom:updated>2025-12-30T19:17:23.841Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to easily limit the sub collections searched by collectionGroup query using a pathPrefix.</h4><p>In this tutorial, you will learn:</p><ol><li>The big problem with collectionGroup.</li><li>How to solve the problem.</li></ol><p>When you’re done, you’ll be using collectionGroup like a pro to target dispersed data with ease.</p><h3>The Problem</h3><p>collectionGroup queries are great for fast searches across dispersed but similar-use-case collections. But they have one problem: they can return too much data. For example:</p><pre>db.collectionGroup(&quot;some-collection-id&quot;);</pre><p>Gives you every collection and subcollection with the ID: &quot;some-collection-id&quot;. If your database structure has two paths:</p><pre>collection1/{a-doc}/some-collection-id<br>collection2/{a-doc}/subcollection1/{a-different-doc}/some-collection-id</pre><p>And it turns out you only want data from the sub collections stored down the collection1/{a-doc}/some-collection-id path, tough luck, you’re stuck with everything.</p><h3>The Solution</h3><p>The solution is to use the __name__ field which is attached to every document, an orderBy, startAt, and endAt. I learned how to do this from this Stack Overflow post:</p><p><a href="https://stackoverflow.com/questions/68049541/collectiongroupquery-but-limit-search-to-subcollections-under-a-particular-docum/79857752#79857752">CollectionGroupQuery but limit search to subcollections under a particular document</a></p><p>But I’ve turned the method into a fully fledged function you can copy and paste in and use easily:</p><pre>/**<br> * Performs a collection group query across all similarly named collections in<br> * the database. Uses a path prefix input to create a filter that rejects all<br> * documents that do not have the path prefix on the server-side, reducing<br> * data transfer and client-side processing.<br> *<br> * As of 2025-12-30, Firestore requires the path prefix to have an even number<br> * of segments. Without this, the query will fail. Therefore, if you provide a<br> * path prefix that points to a collection, the function will find the first<br> * and last document in the collection and use them to create the start and<br> * end path prefixes.<br> *<br> * @param {string} collectionGroup - The collection group to query. This is<br> * the name you would usually use to query a single collection.<br> * @param {string} pathPrefix - The path prefix to use for the query. Each<br> * document has a path stored under the `__name__` field. This is the path to<br> * the document from the root of the database. If a document does not have the<br> * path prefix, it will be rejected by the server-side filter.<br> * @param {admin.firestore.Firestore} db - The firestore database instance.<br> * Dependency injection for easier testing.<br> * @returns {Promise&lt;admin.firestore.Query&lt;admin.firestore.DocumentData&gt;&gt;} A<br> * query object that can be extended and modified with additional filters.<br> * @throws {Error} If the pathPrefix points to a collection, but the<br> * collection is empty.<br> * ```<br> */<br>export async function collectionGroupWithPathPrefixQuery(<br>  collectionGroup: string,<br>  pathPrefix: string,<br>  db: admin.firestore.Firestore<br>): Promise&lt;admin.firestore.Query&lt;admin.firestore.DocumentData&gt;&gt; {<br>  let startPathPrefix = pathPrefix;<br>  let endPathPrefix = pathPrefix + &quot;\uf8ff&quot;; // \uf8ff is the high Unicode character for inclusive upper bound<br><br>  const pathParts = pathPrefix.split(&quot;/&quot;);<br><br>  if (pathParts.length % 2 !== 0) {<br>    const collectionRef = db.collection(pathPrefix);<br><br>    const firstSnapshot = await collectionRef.orderBy(&quot;__name__&quot;).limit(1).get();<br><br>    // Requires an index to be built<br>    const lastSnapshot = await collectionRef.orderBy(&quot;__name__&quot;, &quot;desc&quot;).limit(1).get();<br><br>    if (firstSnapshot.empty || lastSnapshot.empty) {<br>      throw new Error(&quot;Collection is empty&quot;);<br>    }<br><br>    startPathPrefix = firstSnapshot.docs[0].ref.path;<br>    endPathPrefix = lastSnapshot.docs[0].ref.path;<br>  }<br><br>  const query = db.collectionGroup(collectionGroup).orderBy(&quot;__name__&quot;).startAt(startPathPrefix).endAt(endPathPrefix);<br><br>  return query;<br>}</pre><p>In short, the great thing about this method is the following:</p><ol><li>It uses orderBy to make the database query on the server side.</li><li>This saves data being sent to the client, decreasing query completion time, and data transfer costs.</li><li>It returns the query builder so you can add your own statements to it if you like.</li></ol><h3>Final Words</h3><p>I hope you find this helpful, and it lets you use collectionGroup queries in places you’ve never thought to use them, or speeds up your code in places you’re already using them!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8e32ed0cc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-limit-collectiongroup-queries-to-a-particular-path-ba8e32ed0cc0">How To Limit CollectionGroup Queries to a Particular Path</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Typescript NPM Package For a Cloudflare Worker]]></title>
            <link>https://medium.com/full-stack-engineer/how-to-build-a-typescript-npm-package-for-a-cloudflare-worker-653fef2fdfe2?source=rss----8f1c7cdc1132---4</link>
            <guid isPermaLink="false">https://medium.com/p/653fef2fdfe2</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <dc:creator><![CDATA[Connor the Wise]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 16:06:38 GMT</pubDate>
            <atom:updated>2026-08-10T21:24:22.919Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to architect your NPM package for fast development, small size, and simple deployment to the package repository.</h4><p>In this tutorial, you will learn:</p><ol><li>How to architect your Cloudflare Worker-focused NPM package.</li><li>How to publish your package on NPM.</li></ol><p>Once you’re done, you’ll have everything you need to release Cloudflare Worker packages fast!</p><h3>Step 1 — How To Architect Your Package</h3><h4>The Overall Structure</h4><p>I recommend this package structure:</p><pre>📁 ./<br>├── 📁 test/<br>│   └── (... your tests)<br>├── 📁 src/<br>│   └── (... your source code)<br>├── 📄 .gitignore<br>├── 📄 LICENCE<br>├── 📄 README.md<br>├── 📄 package.json<br>├── 📄 tsconfig.json</pre><p>It has everything you need:</p><ol><li>The obligatory package.json to define your package.</li><li>A dedicated place for your source code: /src</li><li>A dedicated place for testing: /test</li><li>A copyright licence.</li><li>A README.md introducing people to your package.</li><li>tsconfig.json for configuring the TypeScript compilation step.</li><li>.gitignore for keeping things like node_modules and your compiled package distribution out of the repo.</li></ol><p>Most importantly, it’s a simple base that’s easy to build from. A detailed explanation of the most important parts is below.</p><h4>The package.json</h4><p>This is the structure as of 2025–12–24:</p><pre>{<br>  &quot;name&quot;: &quot;my-package-name&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;description&quot;: &quot;My package description.&quot;,<br>  &quot;author&quot;: &quot;Connor Skelland&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;=18.0.0&quot;<br>  },<br>  &quot;keywords&quot;: [<br>    &quot;something&quot;,<br>    &quot;something else&quot;<br>  ],<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: {<br>      &quot;import&quot;: &quot;./dist/index.js&quot;,<br>      &quot;types&quot;: &quot;./dist/index.d.ts&quot;<br>    }<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;vitest run&quot;,<br>    &quot;clean&quot;: &quot;tsc --build --clean&quot;,<br>    &quot;build&quot;: &quot;tsc --build&quot;,<br>    &quot;build:watch&quot;: &quot;tsc --watch&quot;,<br>    &quot;prepublishOnly&quot;: &quot;npm run test &amp;&amp; npm run clean &amp;&amp; npm run build&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@cloudflare/workers-types&quot;: &quot;^4.20250816.0&quot;,<br>    &quot;@types/node&quot;: &quot;^24.3.0&quot;,<br>    &quot;typescript&quot;: &quot;^5.9.2&quot;,<br>    &quot;vitest&quot;: &quot;^3.1.0&quot;<br>  },<br>  &quot;files&quot;: []<br>}</pre><p>Here is the purpose behind each of these options:</p><ul><li><strong>name</strong><br>Your package’s unique identifier on NPM. This is how users will install your package: npm install my-package-name</li><li><strong>version</strong><br>Current version of your package (follows <a href="https://semver.org/">semver</a>). Start at 0.1.0 and increment with each release. NPM uses this to track updates.</li><li><strong>description</strong><br>Brief summary of what your package does. Appears in NPM search results and helps users understand your package.</li><li><strong>author</strong><br>Your name or organization. Shows who maintains the package.</li><li><strong>license</strong><br>Type of license (e.g., MIT, ISC). Tells users how they can legally use your code. MIT is very permissive.</li><li><strong>engines</strong><br>Minimum Node.js version required. &gt;=18.0.0 ensures users have a Node version that supports your code.</li><li><strong>keywords</strong><br>Array of search terms. Helps people discover your package on NPM when searching for related topics.</li><li><strong>type</strong><br>Set to &quot;module&quot; for ES modules. Critical for Cloudflare Workers — enables modern import/export syntax instead of old require().</li><li><strong>types</strong><br>Location of TypeScript type definitions. Points to dist/index.d.ts so TypeScript users get autocomplete and type checking.</li><li><strong>exports</strong><br>Defines package entry points. Modern way to specify what users get when they import your package.</li><li><strong>exports[&quot;.&quot;]</strong><br>The default/main entry point. The &quot;.&quot; means this is what users get when they do import pkg from &#39;my-package-name&#39;.</li><li><strong>exports[&quot;.&quot;].import</strong><br>Points to your compiled JavaScript. The actual code that runs when someone imports your package.</li><li><strong>exports[&quot;.&quot;].types</strong><br>Points to your type definitions. Tells TypeScript where to find type information.</li><li><strong>scripts</strong><br>Commands you can run with npm run. Automates common tasks like testing and building.</li><li><strong>scripts.test</strong><br>Runs vitest run. Executes your test suite once. I prefer single execution</li><li><strong>scripts.clean</strong><br>Runs tsc --build --clean. Removes all compiled files from the dist folder (cleanup before rebuilding).</li><li><strong>scripts.build</strong><br>Runs tsc --build. Compiles your TypeScript code to JavaScript and generates type definitions using the TypeScript compiler.</li><li><strong>scripts.build:watch</strong><br>Runs tsc --watch. Continuously watches for changes and rebuilds automatically (useful during development).</li><li><strong>scripts.prepublishOnly</strong><br>Runs npm run test &amp;&amp; npm run clean &amp;&amp; npm run build. Lifecycle hook — tests, cleans, and builds your package before publishing to NPM (prevents publishing stale, broken, or unbuilt code).</li><li><strong>devDependencies</strong><br>Tools needed for development only. These aren’t installed when users add your package to their project.</li><li><a href="http://twitter.com/cloudflare/workers-types"><strong>@cloudflare/workers-types</strong></a><br>TypeScript types for Cloudflare Workers. Provides autocomplete and type checking for Workers-specific APIs.</li><li><a href="http://twitter.com/types/node"><strong>@types/node</strong></a><br>TypeScript types for Node.js. Provides types for Node.js built-in modules. A large number of these are <a href="https://developers.cloudflare.com/workers/runtime-apis/nodejs/">polyfilled by Cloudflare Workers</a>.</li><li><strong>typescript</strong><br>The TypeScript compiler. Enables writing type-safe code.</li><li><strong>vitest</strong><br>Fast testing framework. Modern, fast alternative to Jest with great TypeScript support.</li><li><strong>files</strong><br>Whitelist of files to publish. Works like a reverse .gitignore — only listed files/folders get published. Empty means everything is included.</li></ul><p>If you want more information, you can read the npm documentation:</p><p><a href="https://docs.npmjs.com/cli/v11/configuring-npm/package-json">package.json | npm Docs</a></p><h4>The tsconfig.json</h4><p>This is the tsconfig.json as of 2025–12–25:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;module&quot;: &quot;nodenext&quot;,<br>    &quot;target&quot;: &quot;esnext&quot;,<br>    &quot;types&quot;: [&quot;@cloudflare/workers-types&quot;],<br>    &quot;declaration&quot;: true,<br><br>    // Opinionated options below<br>    &quot;noUncheckedIndexedAccess&quot;: true,<br>    &quot;noUnusedLocals&quot;: true,<br>    &quot;noUnusedParameters&quot;: true,<br>    &quot;noPropertyAccessFromIndexSignature&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;verbatimModuleSyntax&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;noUncheckedSideEffectImports&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src/**/*&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;, &quot;test&quot;]<br>}</pre><p>The top set of options in compilerOptions are technically all you need. The remaining compilerOptions are opinionated settings that force you to write solid TypeScript. Delete at your leisure.</p><p>Here’s the purpose of all the options:</p><ul><li><strong>rootDir</strong><br>The root directory of your source code. Set to ./src so TypeScript knows where to find your source files.</li><li><strong>outDir</strong><br>The output directory for compiled code. Set to ./dist so all compiled JavaScript and type definitions go in one place.</li><li><strong>module</strong><br>The module code generation mode. nodenext ensures compatibility with modern Node.js ESM (ES Modules). See also TypeScript Module Documentation.</li><li><strong>target</strong><br>The target ECMAScript version. esnext compiles to the latest JavaScript features, making it perfect for the Cloudflare Workers runtime, which run in <a href="https://developers.cloudflare.com/workers/reference/how-workers-works/#isolates">V8 engine isolates</a>.</li><li><strong>types</strong><br>Type definitions to include. <a href="http://twitter.com/cloudflare/workers-types">@cloudflare/workers-types</a> gives you autocomplete and type checking for Cloudflare Workers APIs.</li><li><strong>declaration</strong><br>Generates .d.ts declaration files. Set to true so TypeScript creates type definition files that consumers of your package can use.</li><li><strong>noUncheckedIndexedAccess</strong><br>Enforces strict checking of indexed access. Prevents bugs by making TypeScript warn when accessing array/object properties that might not exist.</li><li><strong>noUnusedLocals</strong><br>Enforces that all local variables are used. Helps keep code clean by catching unused variables.</li><li><strong>noUnusedParameters</strong><br>Enforces that all parameters are used. Catches unused function parameters, improving code quality.</li><li><strong>noPropertyAccessFromIndexSignature</strong><br>Prevents accessing undefined properties. Forces you to use bracket notation for dynamic property access, preventing typos.</li><li><strong>strict</strong><br>Enforces strict type checking. Enables all strict type checking options — catches more bugs at compile time.</li><li><strong>verbatimModuleSyntax</strong><br>Forces explicit type imports. Requires you to write import type when only importing types — making bundling more efficient.</li><li><strong>isolatedModules</strong><br>Enforces strong module boundaries. Each file must be independently compilable to ensure compatibility with bundlers and build tools.</li><li><strong>noUncheckedSideEffectImports</strong><br>Prevents importing non-existent modules. Catches typos in import statements before runtime.</li><li><strong>skipLibCheck</strong><br>Skips checking external library types. Speeds up compilation by not type-checking node_modules.</li><li><strong>forceConsistentCasingInFileNames</strong><br>Enforces consistent casing in file names. Prevents issues when moving code between case-sensitive (Linux) and case-insensitive (Windows/Mac) filesystems.</li><li><strong>include</strong><br>Files to include in compilation. [&quot;src/**/*&quot;] tells TypeScript to compile everything in the src folder.</li><li><strong>exclude</strong><br>Files to exclude from compilation. Prevents TypeScript from unnecessarily processing node_modules, dist, and test folders.</li></ul><p>If you want more information, you can read the tsconfig reference:</p><p><a href="https://www.typescriptlang.org/tsconfig/">TSConfig Reference - Docs on every TSConfig option</a></p><h4>Why the simple structure?</h4><p>My biggest pet peeve in a project is root directory detritus. Even something as messy as this makes my skin crawl:</p><pre>📁 ./<br>├── 📁 .cursor/<br>├── 📁 static/<br>├── 📁 scripts/<br>├── 📁 src/<br>├── 📄 .DS_Store<br>├── 📄 .env<br>├── 📄 .env.example<br>├── 📄 .gitignore<br>├── 📄 .grabit<br>├── 📄 .npmrc<br>├── 📄 .prettierignore<br>├── 📄 .prettierrc<br>├── 📄 README.md<br>├── 📄 eslint.config.js<br>├── 📄 mise.toml<br>├── 📄 package-lock.json<br>├── 📄 package.json<br>├── 📄 svelte.config.js<br>├── 📄 tsconfig.json<br>├── 📄 vite.config.ts<br>├── 📄 vitest-setup-client.ts<br>├── 📄 wrangler.jsonc</pre><p>Sometimes you need every bit of it. But it’s still an ugly cognitive overload. Starting from a simple template means you own any extra files that end up in your root. With ownership comes understanding and the absolute permission to tidy and optimise without fear.</p><p>In short, I’ve kept it simple to keep you nimble.</p><h4>Package Extensions</h4><p>If you’d prefer decisions to be made for you, here are some things you may want to add:</p><ol><li>A <a href="https://prettier.io/">formatter</a>.</li><li><a href="https://typicode.github.io/husky/">Pre-commit hooks</a>.</li><li>/docs folder for extra examples.</li><li>/scripts folder for custom repo actions.</li><li><a href="https://github.com/features/actions">CI/CD pipeline</a>.</li><li><a href="https://github.com/changesets/changesets">Automated versioning</a>.</li></ol><p>I’ve added links to the most recommended tools, where applicable.</p><h3>Step 2 — Create an Account on NPM</h3><p>If you don’t have one already, visit the sign up page:</p><p><a href="https://www.npmjs.com/signup">https://www.npmjs.com/signup</a></p><p>Sign up using:</p><ul><li><strong>username </strong>— Choose something fairly bland but identifiable. Or, if you already have a profressional/ developer username, use that. For me, that’s connor56.</li><li><strong>email</strong> — Choose a stable email address you have access to and read regularly. If your email provider allows aliases, you could always add +npm to the front to make them easy to sort.</li></ul><p>You’ll be asked to verify your email by a One-Time-Passcode. Once complete you’ll be on the profile home screen.</p><h4>Private Email Alias</h4><p>If you dislike the idea of making your private email address public but still want to use it for communication, use a relay service. For example, ProtonMail has its Proton Pass manager, which lets you set up aliases:</p><p><a href="https://proton.me/pass">Proton Pass: Free password manager with identity protection | Proton</a></p><p>If you don’t use ProtonMail, you could also use something like SimpleLogin:</p><p><a href="https://simplelogin.io/">SimpleLogin | Open source anonymous email service</a></p><h3>Step 3 — Build and Publish Your Package</h3><p>Once you’ve created your package and you’re ready to publish, you need to log in to your account on the npm CLI. Do this with:</p><pre>npm login</pre><p>You’ll be taken to the npm login screen and sent another One-Time Passcode. Fill this in on the web browser, and you’ll grant your npm CLI permission to use your account:</p><pre>➜  git:(main) ✗ npm login<br>npm notice Log in on https://registry.npmjs.org/<br>npm notice Security Notice: Classic tokens have been revoked. Granular tokens are now limited to 90 days and require 2FA by default. Update your CI/CD workflows to avoid disruption. Learn more https://gh.io/all-npm-classic-tokens-revoked<br>Login at:<br>https://www.npmjs.com/login?next=/login/cli/asdkfh27987234-askh7w372kjasiuywe-127323ns<br>Press ENTER to open in the browser...<br><br>Logged in on https://registry.npmjs.org/.<br>➜  git:(main) ✗</pre><p>Before publishing, you may need to bump the package version if you’ve made changes:</p><pre>npm bump patch<br>npm bump minor<br>npm bump major</pre><p>Then publish with:</p><pre>npm publish</pre><p>If you’ve left the prepublishOnly script in your package.json this will run all of your tests, delete all of the code from the /dist folder, and rebuild everything. If there are any issues, publishing will fail.</p><p>If you’re being told you need to pay to publish a private package, it’s probably because you have a <a href="https://docs.npmjs.com/about-scopes">scope</a> in front of the package name. For example:</p><pre>@connor56/some-package</pre><p>When you use a scope the npm CLI assumes you want to publish your package privately. You can prevent this by running:</p><pre>npm publish --access public</pre><p>That’s it, you’ll see your package on your NPM account.</p><h3>Final Words</h3><p>Well, there you are! I hope this helps you set up and build your own reusable software for Cloudflare Workers. If it’s your first time releasing anything on NPM, let me know if the explanations help you to get over the first publication nerves.</p><p>Happy publishing!</p><h3>Subscribe If</h3><p>You like regular batteries-included tutorials that help you become a master Full Stack Developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653fef2fdfe2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/full-stack-engineer/how-to-build-a-typescript-npm-package-for-a-cloudflare-worker-653fef2fdfe2">How to Build a Typescript NPM Package For a Cloudflare Worker</a> was originally published in <a href="https://medium.com/full-stack-engineer">Full Stack Wizardry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>