# Archives of Aditya Khare - Lessons from a Self-taught Dev's Life — Full Markdown > I share my opinions on the life of a Software Developer within and beyond Tech with the help of short, easy-to-digest Tutorials and Articles. Base URL: https://adityakhare.com/ Author: Aditya Khare This file concatenates every published article as Markdown for LLM ingestion. Prefer per-article .md URLs from [/llms.txt](https://adityakhare.com/llms.txt) when you only need one page. --- # Containers, Sandboxes, AI and everything in between **URL:** https://adityakhare.com/articles/containers-sandboxes-ai-and-everything-in-between **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2026-11-20T11:07:00.000Z **Updated:** 2026-12-03T13:09:51Z --- **Summary:** A practical guide to Sandboxes and AI agent security. Learn microVM isolation, run coding agents safely, and compare tools in this space. AI coding agents are getting really good at executing tasks independently. They can ~~steal you environment variables~~ read your codebase, install dependencies, execute shell commands, run tests, modify files and even start Docker containers. But there is a problem, a big one actually. Would you give an AI agent unrestricted access to your machine and trust that it will always do the right thing? _I wouldn’t_. ![](https://cdn.sanity.io/images/r7i2kebp/production/ff6c1db7ff14b0b28dab92f5152a106a69770e26-598x420.jpg) This is where S**andboxing** becomes interesting. Let’s understand what sandboxes are, how they work, and actually run an AI coding agent inside one. ## Containers are not sandboxes but they can be We have been using containers for years. They provide process isolation, file system isolation and resource control using Linux namespaces and cgroups. However, containers share the host’s Linux [kernel](https://en.wikipedia.org/wiki/Kernel_%28operating_system%29). That means a container is not automatically a strong security boundary, especially when you’re running untrusted code or giving an autonomous agent access to the environment. Now, Sandboxes aren’t very different from containers. The definition for Sandboxing doesn’t hold any meaning except that it’s more of > a security boundary that restricts what an application can do. Therefore, If you run your container with limited process capabilities and access to the host machine, it can typically be considered as a sandbox. With a normal docker container ```sh docker run --rm python:3.12 python app.py ``` You get: - Filesystem isolation. - Process namespace isolation. - Resource management. - Network isolation depending on configuration. - Default security restrictions. _But the application still shares the host kernel._ ```sh docker run --rm \ --network none \ --memory=128m \ --cpus=0.5 \ --pids-limit=32 \ --read-only \ --cap-drop=ALL \ --security-opt=no-new-privileges \ --security-opt seccomp=/path/to/seccomp.json \ --user 10001:10001 \ python:3.12 \ python app.py ``` Now you've added several restrictions: - No network access. - 128 MB memory limit. - Half a CPU. - Maximum 32 processes. - Read-only root filesystem. - No Linux capabilities. - No privilege escalation. - Custom syscall restrictions. - Non-root execution. This is a much more hardened container**_ i.e. sandbox._** Let’s look at the distinction: | Technology | What it provides | | --- | --- | | Container | Application packaging and process isolation | | Linux sandbox | Restricted access to system resources | | MicroVM | Hardware-assisted isolation with its own kernel | A container answers: Where should my application run? A sandbox answers: What is this application allowed to access? And a microVM adds another layer by giving the workload its own kernel. ## Meet Docker Sandboxes Basically the Docker team came full circle from moving away from microVMs to containers to just building a hybrid of it themselves when they introduced [Docker Sandboxes](https://docs.docker.com/ai/sandboxes/) specifically for running AI coding agents in isolated environments. Each sandbox runs inside a lightweight microVM with: - Its own Linux kernel. - Its own filesystem. - Its own Docker Engine. - Its own network environment. - Controlled access to host files and credentials. Why does the separate Docker Engine matter? Consider a typical approach where you run an AI agent inside a container and mount the host Docker socket: ```sh -v /var/run/docker.sock:/var/run/docker.sock ``` This is convenient, but it also gives the agent access to your host Docker daemon. An agent that can control your Docker daemon can potentially gain access to much more than the project it was supposed to work on. Docker Sandboxes solve this differently. The agent gets its own Docker Engine inside the microVM. It can build images, start containers and run Docker Compose without controlling the host Docker daemon. That’s a meaningful architectural difference. ## Let’s run our first Sandbox For this tutorial, let’s assume: - Ubuntu 24.04 or later. - A 64-bit machine with KVM support. - Claude Code installed through Docker’s supported agent workflow. - An existing Node.js project. Docker Sandboxes also supports macOS and Windows, but the installation requirements differ. ### Step 1: Install Docker Sandboxes Docker provides a standalone sbx CLI. You don’t need Docker Desktop or a host Docker Engine just to use the CLI. For Ubuntu, you can install only the sandbox package: ```sh curl -fsSL https://get.docker.com | sudo REPO_ONLY=1 sh sudo apt install docker-sbx ``` Check that KVM is available by running: `lsmod | grep kvm` Your output should contain something like `kvm_intel `or` kvm_amd` For local Linux sandboxes, your account also needs access to KVM: ```sh sudo usermod -aG kvm $USER ``` Log out and back in, then authenticate: ```sh sbx login ``` Refer to Docker’s installation guide for other operating systems and prerequisites. ### Step 2: Navigate to your project Let’s use a Node.js application as an example. ```sh cd ~/projects/my-node-app ``` Normally, you would start your coding agent directly from this directory. Instead, let’s launch it inside a sandbox: ```sh sbx run --name node-agent claude ``` That’s it. Your agent is now running inside a Docker Sandbox. The first execution might take longer because Docker needs to pull the agent image. Subsequent executions can reuse cached images. If this is your first run, Docker may ask you to select a network policy. Choose _Balanced_ for this tutorial. ### Step 3: Give the agent some work Try something simple: ```text Inspect this Node.js project. Install the required dependencies, run the existing tests, identify any failures, and fix them. Do not modify files outside the project. ``` The agent can now execute commands, install packages and run containers inside its isolated environment. _One important detail:_ when you run `sbx run `from a project directory, that directory is mounted read-write into the sandbox by default. So the agent can modify your actual project files. The rest of the host filesystem remains outside its normal sandbox access. If you want the agent to work on a private copy instead, use Docker’s clone workflow. ### Step 4: Inspect your running sandboxes Open another terminal: ```sh sbx ls ``` You can inspect the active sandbox, its agent, status and workspace. You can also inspect its network rules: ```sh sbx policy ls ``` For example, if your application needs to download npm packages, you can explicitly allow the npm registry: ```sh sbx policy allow network registry.npmjs.org ``` This is an important part of sandboxing. Filesystem isolation alone isn’t enough. An agent with unrestricted network access can still communicate with external services, download malicious dependencies or send data outside your environment. **Control both.** ### Step 5: Clean up Once you’re done: ```sh sbx stop node-agent ``` This stops the sandbox but preserves its state. When you no longer need it: ```sh sbx rm node-agent ``` This removes the sandbox and its internal filesystem, images, containers and other state. Your original host project directory remains unaffected by the cleanup. ### Secrets Docker Sandboxes also handle API keys and [authentication credentials](https://docs.docker.com/ai/sandboxes/configuration/credentials/) for sandboxed agents. You can use the below commands to _set, list and remove_ any secrets used by your agents while never leaving your host system’s OS keychain. ```sh # secret is global by default sbx secret set anthropic # scope a secret to a specific sandbox sbx secret set openai --sandbox my-sandbox # both commands prompt you for the secret value interactively ``` ```sh sbx secret ls SCOPE SERVICE SECRET (global) github gho_GCaw4o****...****43qy ``` ```sh # Remove a secret sbx secret rm github # To remove a sandbox-scoped secret, pass --sandbox sbx secret rm github --sandbox my-sandbox ``` The store backing `sbx secret set` depends on your operating system: - macOS: the system Keychain. - Windows: the Windows Credential Manager. - Linux: the Secret Service exposed by your desktop keyring, such as GNOME Keyring or KDE Wallet. You see? The commands are the same as managing a container. That’s the beauty of disposable execution environments. ## What’s happening under the hood? Let’s simplify the architecture. ```text Developer | v AI Agent | v Docker Sandbox | ------------------------ | | v v MicroVM Network Proxy | | v v Private Docker Network Rules Engine | | v v Internet Containers | v Test / Build --------------------------- HOST MACHINE --------------------------- Host Docker Engine Credentials Other Files Operating System ``` There are a few important boundaries here: **_Hypervisor isolation:_** Each sandbox has its own Linux kernel. This is different from ordinary containers that share the host kernel. **_Network isolation: _**Outbound traffic is routed through a policy-controlled proxy. Destinations can be allowed or blocked. **_Docker Engine isolation:_** The agent communicates with its private Docker Engine rather than the host daemon. **_Credential isolation:_** Docker provides a credential proxy mechanism so supported agent credentials can remain outside the microVM. **_One caveat:_** explicitly shared workspaces and other configured integrations still expose the resources you grant them. A sandbox is only as restrictive as its configuration and security boundaries. ## What about Other tools? Now just as for their containerisation service which is built on the [Open Container Initiative](https://opencontainers.org/) and have other players in the space like [Podman](https://podman.io/) and [Apple containers](https://github.com/apple/container) (yeah, they have one too). Docker isn’t the first company or project to work on sandboxing. There are several interesting alternatives, each solving the same problem in a slightly different way. So if you don’t want to use docker, some of the other tools that I have used are: #### Bubblewrap (bwrap) [GitHub: containers/bubblewrap](https://github.com/containers/bubblewrap) Bubblewrap is a lightweight Linux sandboxing tool that uses namespaces to construct isolated environments. You can control which directories are visible, create separate PID and network namespaces, and apply additional restrictions. Example: ```sh bwrap \ --ro-bind /usr /usr \ --ro-bind /bin /bin \ --proc /proc \ --dev /dev \ --tmpfs /tmp \ --unshare-net \ /bin/sh ``` This is a minimal illustration, not a complete production security profile. Real applications need additional filesystem and runtime dependencies. Bubblewrap is useful when you want low-level control over process isolation without introducing a full VM. #### Firejail [Official documentation](https://firejail.wordpress.com/documentation-2/) Firejail is another Linux sandboxing tool. It uses namespaces, seccomp-bpf and Linux capabilities to restrict applications. Its interface is particularly simple: ```sh firejail firefox ``` You can also create application-specific profiles and restrict filesystem or network access. For example: ```sh firejail --net=none my-program ``` Firejail is particularly useful for sandboxing desktop applications and individual processes. I also found a great practical guide on how to use these sandboxing tools with popular AI Agent harnesses like Opencode, Claude, Pi etc. You can look at the [agent sandboxing guidelines](https://github.com/odoo/odoo/tree/20.0/setup/sandboxing) of Odoo which is one of the largest open-source python codebases. #### So, Which one should you use? If you’re building an AI agent that needs to execute arbitrary commands, install packages, build containers and run tests, Docker Sandboxes are an interesting starting point. If you’re building your own execution infrastructure, understanding tools like Bubblewrap will give you a much better understanding of the underlying security trade-offs. ### Special Mentions We also have other tools to run microVMs and sandbox specific work spaces. One such fantastic tool that comes to mind was recently launched by CJ from Syntax and is called [Devvm](https://github.com/devvmhq/devvm). I haven’t used it myself but as a fan of CJ’s work, I know that the stuff he builts really comes from a place of providing a great Developer Experience to the users. #### Cloud Sandboxes The AI boom has also brought a bunch of new cloud providers into the space. These platforms let us run agents inside isolated cloud microVMs, in fully sand boxed environments that we can provision, spin up, and tear down on demand all through from your application’s code. Some popular options worth checking out are: - [Boat](https://boat.dev/) - [Daytona](https://www.daytona.io/) - [Modal](https://modal.com/) - [Archil](https://docs.archil.com/compute/sandboxes/introduction) And it's not just the new players offering this. Your favourite cloud providers are getting into the game too. For example, Cloudflare recently introduced [Sandboxes](https://developers.cloudflare.com/sandbox/) on top of its Workers platform. ## Takeaway The way we build software is changing. Earlier, we mostly worried about where our application would run, how it would scale and how we would deploy it. Now, we’re also building systems that allow software to make decisions and execute actions independently. That introduces a different security problem. We shouldn’t have to trust every command an AI agent or the company who made it generates. We should be able to control what happens when that command executes. These giants have already leached off on open-source (and closed) IP enough to take away our jobs. The least we can do is make sure they don’t have our credentials too (I mean whatever is left of it) Containers made application packaging easier. Sandboxes make controlled execution possible. And as AI agents become more autonomous, I think understanding both will become an essential part of back end and infrastructure engineering. > Don’t just make your agents capable. > > Give them a controlled environment to be capable in. Until Next Time, **Happy ~~Prompting~~Coding👋** ## Further reading & references 1. [Docker: A New Approach for Coding Agent Safety](https://www.docker.com/blog/docker-sandboxes-a-new-approach-for-coding-agent-safety/) 2. [Docker: Docker Sandboxes — Run Claude Code and Other Coding Agents Unsupervised](https://www.docker.com/blog/docker-sandboxes-run-claude-code-and-other-coding-agents-unsupervised-but-safely/) 3. [Docker Sandboxes — Official Documentation](https://docs.docker.com/ai/sandboxes/) 4. [Docker Sandboxes — Isolation Layers](https://docs.docker.com/ai/sandboxes/security/isolation) 5. [Bubblewrap — Official GitHub Repository](https://github.com/containers/bubblewrap) 6. [Firejail — Documentation](https://firejail.wordpress.com/documentation-2/) *HTML:* https://adityakhare.com/articles/containers-sandboxes-ai-and-everything-in-between *Markdown:* https://adityakhare.com/articles/containers-sandboxes-ai-and-everything-in-between.md --- # Stop fetching everything just to process one element at a time **URL:** https://adityakhare.com/articles/stop-fetching-everything-just-to-process-one-element-at-a-time **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2026-11-18T18:36:19.750Z **Updated:** 2026-11-18T18:36:52Z --- **Summary:** Useful tips on optimizing performance of your server using better practices like iterators and generators Let's start with a familiar piece of code. ```typescript const longList = await fetchAllElementsInMemory(); for (const item of longList) { process(item); } ``` Looks innocent, right? Fetch the data, store it in an array, iterate over it, and do whatever you need to do. But here's the problem. **What if `fetchAllElementsInMemory()` returns 10 million records?** Do you really need all 10 million records sitting in memory before you can start processing the first one? Probably not. And yet, this is exactly what we do in a lot of applications. We fetch everything, allocate memory for everything, wait for everything to finish loading, and _then_ start processing it. It's a little like ordering an entire restaurant's menu before taking your first bite. What if there was a better way? Meet **iterators and generators**. ## First, what exactly is an iterator? An iterator is a mechanism that gives you access to elements of a collection one at a time, without requiring you to load the entire collection upfront. Think of it as a vending machine. You press a button, get one item, consume it, and press the button again for the next one. You don't need to empty the entire vending machine onto the floor before choosing what you want. That's essentially what an iterator does. Instead of returning an entire collection: ```typescript function fetchUsers(): User[] { // Fetch and return 1 million users } ``` You expose a way to retrieve the next user whenever the consumer is ready. Conceptually: ```typescript function getNextUser(): User | null { // Return the next user } ``` The consumer controls when to request the next element. This introduces an important distinction: - **Eager evaluation:** Calculate or fetch everything upfront. - **Lazy evaluation:** Calculate or fetch an element only when it's needed. And that's where iterators become interesting. ## How does this actually improve space and time complexity? Let's take an example. You have 10 million users in your database, and you need to calculate how many of them are active. The traditional approach might look something like this: ```typescript const users = await fetchAllUsers(); let activeCount = 0; for (const user of users) { if (user.isActive) { activeCount++; } } ``` What's happening here? 1. Fetch all 10 million users. 2. Deserialize them. 3. Allocate memory for the entire collection. 4. Start processing. 5. Calculate the result. If each user object occupies approximately 1 KB in memory, you're potentially looking at around 10 GB of object data alone. That's before accounting for JavaScript object overhead, arrays, temporary allocations, and other application memory. Now imagine doing this across multiple concurrent requests. Your server's RAM is going to have a very interesting day. Let's look at the complexity. | Metric | Fetch Everything | Lazy iteration | | --- | --- | --- | | Total processing time | O(n) | O(n) | | Additional processing memory | O(n) | O(1) | | Time to first result | After full fetch | Potentially immediate | | Early termination | Still fetched everything | Can stop early | Notice something important? Iterators do not magically improve the overall time complexity of processing all n elements. If you need to inspect every record, you still need O(n) time. **What they improve is:** - Additional memory consumption. - Time to first result. - Ability to stop processing early. - Avoidance of unnecessary intermediate collections. That distinction matters. If you're only interested in the first 100 matching records, why fetch and process all 10 million? An iterator allows you to stop as soon as you've got what you need. ## Iterators and generators in TypeScript JavaScript (and therefore TypeScript) has a built-in iteration protocol. There are two important concepts: **Iterable:** An object that knows how to provide an iterator. **Iterator:** An object that knows how to produce the next value. An iterator implements a `next()` method that returns an object containing: ```javascript { value: something, done: false } ``` When there are no more values: ```javascript { value: undefined, done: true } ``` TypeScript provides two interfaces to understand this: ```typescript interface Iterator { next(): IteratorResult; } interface Iterable { [Symbol.iterator](): Iterator; } ``` You don't usually need to implement these interfaces manually because JavaScript already provides them for arrays, maps, sets, and other built-in collections. ### Generators: The easiest way to create iterators This is where things get really nice. Instead of manually implementing `next()`, you can use generator functions. A generator function is declared using `function*` and produces values using `yield`. Let's see: ```javascript function* generateNumbers() { yield 1; yield 2; yield 3; } const numbers = generateNumbers(); console.log(numbers.next()); // { value: 1, done: false } console.log(numbers.next()); // { value: 2, done: false } console.log(numbers.next()); // { value: 3, done: false } console.log(numbers.next()); // { value: undefined, done: true } ``` Every time `next()` is called, execution resumes from where the previous `yield` left off. This is the important part. The generator doesn't calculate all the values and store them somewhere before returning. It pauses, gives you a value, and waits until you ask for the next one. You can also use it directly with `for...of`: ```javascript function* generateNumbers() { yield 1; yield 2; yield 3; } for (const number of generateNumbers()) { console.log(number); } ``` Much cleaner. ### Let's solve our original problem Remember our 10 million users? Let's create a generator that produces users one at a time. ```javascript function* getUsers() { for (let i = 1; i <= 10_000_000; i++) { yield { id: i, isActive: i % 2 === 0 }; } } let activeCount = 0; for (const user of getUsers()) { if (user.isActive) { activeCount++; } } console.log(activeCount); ``` We never create an array containing 10 million user objects. We generate one user, process it, and move to the next one. The generator maintains only the state required to resume execution. Additional memory for this example is O(1), excluding output and runtime overhead. ### What if fetching the data itself is asynchronous? This is a very common scenario in backend applications. Imagine fetching records from an external API or reading data from a paginated endpoint. You don't want to fetch every page upfront. TypeScript has something for this too: **Async Iterators and Async Generators**. Notice the difference: - `function*` creates a synchronous generator. - `async function*` creates an asynchronous generator. Here's an example: ```javascript async function* fetchUsers() { let page = 1; while (true) { const response = await fetch( `https://api.example.com/users?page=${page}` ); const users = await response.json(); if (users.length === 0) { break; } for (const user of users) { yield user; } page++; } } ``` And consuming it: ```javascript let activeCount = 0; for await (const user of fetchUsers()) { if (user.isActive) { activeCount++; } } ``` Look at what's happening: 1. Fetch the first page. 2. Yield its users individually. 3. Process them. 4. Fetch the next page when the current page has been consumed. 5. Continue until there are no more pages. We never need to maintain all 10 million records in memory. **One important detail:** this example buffers one API page at a time. If an API returns 10,000 records per page, those 10,000 records still occupy memory. The memory requirement is therefore O(page size), not literally zero. That's lazy evaluation in practice. ## Iterators in Go Now let's switch to Go. Go has always had a straightforward way of iterating over collections: ```golang for _, user := range users { process(user) } ``` But here's the catch. If `users` is already a slice containing 10 million records, you've already paid the memory cost of loading those records. The `range` keyword itself doesn't make iteration lazy. A slice is still a slice. Go introduced a more interesting approach with **range-over-function iterators in Go 1.23**. This allows us to write custom iterator functions and consume them using the familiar `range` syntax. ### Understanding the iter package Go 1.23 introduced the standard library's `iter` package. It provides two important iterator types: ```golang type Seq[V any] func(yield func(V) bool) type Seq2[K, V any] func(yield func(K, V) bool) ``` Let's simplify this. - `Seq` produces one value at a time. - `Seq2` produces two values at a time, commonly a key-value or index-value pair. The `yield` function is how the iterator hands values to the consumer. If `yield` returns `false`, it means the consumer wants to stop iterating. Let's implement one: ```golang package main import ( "fmt" "iter" ) func GenerateNumbers() iter.Seq[int] { return func(yield func(int) bool) { for i := 1; i <= 5; i++ { if !yield(i) { return } } } } func main() { for num := range GenerateNumbers() { fmt.Println(num) } } ``` Output: ```text 1 2 3 4 5 ``` What's interesting here? We aren't returning a slice. We're returning a function that knows how to produce values and pass them to the consumer. The consumer controls the iteration. ### What happens when we want to stop early? Let's say we only want the first three numbers. ```golang func main() { count := 0 for num := range GenerateNumbers() { fmt.Println(num) count++ if count == 3 { break } } } ``` Output: ``` 1 2 3 ``` When we use `break`, the generated iteration machinery stops the sequence. The iterator receives `false` from `yield` and should stop producing values. This is especially useful when processing large datasets where you don't necessarily need every record. ### A practical backend example Let's imagine we're reading millions of users from PostgreSQL using Go. The traditional approach might look like this: ```golang users, err := fetchAllUsers(db) if err != nil { return err } for _, user := range users { process(user) } ``` The problem? `fetchAllUsers()` has to construct and return a complete slice before processing begins. Instead, we can expose an incremental database iterator. ```golang package main import ( "database/sql" "iter" ) type User struct { ID int IsActive bool } func Users(db *sql.DB) iter.Seq2[User, error] { return func(yield func(User, error) bool) { rows, err := db.Query( "SELECT id, is_active FROM users", ) if err != nil { yield(User{}, err) return } defer rows.Close() for rows.Next() { var user User if err := rows.Scan( &user.ID, &user.IsActive, ); err != nil { yield(User{}, err) return } if !yield(user, nil) { return } } if err := rows.Err(); err != nil { yield(User{}, err) } } } ``` And consuming it: ```golang func processUsers(db *sql.DB) { for user, err := range Users(db) { if err != nil { // Handle error return } if user.IsActive { // Process active user } } } ``` Notice what we achieved: - We didn't construct a slice of all users. - We scanned a row when the consumer requested the next value. - We allowed early termination. - We kept database resource cleanup inside the iterator. **_A caveat: _**database drivers and databases have their own buffering and cursor behavior. The iterator avoids materializing the entire result set in our application code, but it doesn't guarantee zero buffering throughout the system. Also, the iterator must be consumed for its deferred cleanup to execute. If an iterator is created but never started, its body never runs and no query is opened. #### TypeScript vs Go: What's actually different? Both languages solve the same fundamental problem, but their implementations have some differences. One interesting difference is that TypeScript has supported generators and async generators for quite some time, whereas Go introduced its standardized iterator package and range-over-function support in Go 1.23. Also, Go's iterator model isn't a direct equivalent of JavaScript's `next()`-based iterator protocol. Go uses a push-style callback mechanism: the iterator calls `yield`, rather than the consumer explicitly calling `next()`. Different implementation, same fundamental idea. ## What about Python? Does it have iterators? Absolutely. In fact, Python has a very explicit iterator protocol, and it's one of the core concepts behind how its `for` loops work. There are two important methods: `__iter__() `and` __next__()` An iterable provides an iterator through `__iter__()`. An iterator provides the next element through `__next__()`. When there are no more values, it raises `StopIteration`. Python also has generators, which make implementing iterators extremely convenient. ### Python generators Consider the traditional approach: ```python def get_numbers(): return [i for i in range(10_000_000)] numbers = get_numbers() for number in numbers: process(number) ``` This creates a list containing 10 million integers. Now compare that with: ```python def get_numbers(): for i in range(10_000_000): yield i for number in get_numbers(): process(number) ``` That's it. One keyword changes the behaviour significantly. `yield` suspends the function and preserves its execution state. When the consumer requests another value, execution resumes from where it stopped. ### Python has something even more interesting: Generator expressions Look at this: ```python numbers = [i * i for i in range(10_000_000)] ``` This is a list comprehension. It materializes the entire list. Now: ```python numbers = (i * i for i in range(10_000_000)) ``` This is a generator expression. It produces values lazily. You can even use it directly: ```python total = sum( i * i for i in range(10_000_000) ) ``` You don't need to construct an intermediate list containing 10 million squared numbers. The `sum()` function consumes the iterator and maintains its running total. ### Python's itertools Python takes this idea further with its standard library module `itertools`. It provides building blocks for composing memory-efficient iteration pipelines. For example: ```python from itertools import islice numbers = range(10_000_000) first_hundred = islice(numbers, 100) for number in first_hundred: process(number) ``` Or: ```python from itertools import chain combined = chain( range(1_000_000), range(1_000_000, 2_000_000) ) for number in combined: process(number) ``` Neither operation needs to materialize a new list containing all the values. Python's `itertools` is particularly useful for composing lazy transformations. ### Async iterators in Python Just like TypeScript, Python supports asynchronous iteration. You use: - `async def` - `yield` - `async for` Example: ```python async def fetch_users(): page = 1 while True: users = await fetch_api_page(page) if not users: break for user in users: yield user page += 1 ``` Consumption: ```python async for user in fetch_users(): await process(user) ``` This is useful for asynchronous APIs, network streams, and other I/O-bound workloads. ## Do we actually need generators in production? This is where things get interesting. We have iterators in Go, generators in TypeScript, and generators in Python. But we also have pagination, database cursors, batching, garbage collection, worker pools, and other memory-management techniques. Are generators really necessary when these other techniques already exist? **_My take _**🌶️**_: _** > **Generators deserve a place in production codebases, but they shouldn't be the default solution for every large-data problem.** Let's understand why. ### What problem do generators solve that pagination doesn't? Consider this function: ```typescript async function fetchUsers(): Promise { let page = 1; const users: User[] = []; while (true) { const response = await fetchPage(page); if (response.length === 0) break; users.push(...response); page++; } return users; } ``` We have pagination. But we haven't solved the memory problem. We're still accumulating every record in the `users` array. Now imagine exposing a generator instead: ```typescript async function* fetchUsers() { let page = 1; while (true) { const response = await fetchPage(page); if (response.length === 0) break; for (const user of response) { yield user; } page++; } } ``` The consumer can now process records as they arrive: ```typescript for await (const user of fetchUsers()) { await processUser(user); } ``` The generator provides a clean interface between the data producer and the data consumer. And importantly, the producer doesn't need to know whether the consumer is: - Writing records to another database. - Sending emails. - Generating a CSV. - Calculating statistics. - Filtering records. That's a valuable separation of concerns. ### The strongest argument for generators: Composable data pipelines This is where I think generators really justify themselves. Imagine a production workflow: 1. Fetch users. 2. Filter active users. 3. Filter users who have subscribed to premium. 4. Transform their data. 5. Send them notifications. Without lazy processing, you might end up with: ```javascript const users = await fetchAllUsers(); const activeUsers = users.filter( u => u.isActive ); const premiumUsers = activeUsers.filter( u => u.isPremium ); const notificationData = premiumUsers.map(u => ({ email: u.email, name: u.name })); for (const user of notificationData) { await sendNotification(user); } ``` Look at the intermediate arrays. Depending on the implementation, you're maintaining multiple collections containing references to the same underlying user objects. Even when you're not duplicating every user object, you're allocating additional arrays containing potentially millions of references. Now let's turn this into a lazy pipeline: ```javascript async function* getNotificationUsers() { for await (const user of fetchUsers()) { if (!user.isActive || !user.isPremium) { continue; } yield { email: user.email, name: user.name }; } } ``` Consumption: ```javascript for await (const user of getNotificationUsers()) { await sendNotification(user); } ``` Now each record flows through the pipeline individually. No full-sized intermediate arrays. No need to wait for all users to be fetched. The consumer determines the pace of processing. This is the architectural benefit I'd emphasize. Generators allow us to build reusable, composable transformations without materializing every intermediate result. Python is particularly good at this because of its `itertools` ecosystem. For example: ```python def get_notification_users(users): for user in users: if user.is_active and user.is_premium: yield { "email": user.email, "name": user.name } notifications = get_notification_users(fetch_users()) for user in notifications: send_notification(user) ``` The interesting thing is that `fetch_users()` itself can be a generator. So the entire pipeline can remain lazy, from the source to the final consumer. ### 7.3 Generators are not always better This is where I'd generally avoid them. Consider three scenarios. **_Scenario A: You have 500 records._** ```javascript const users = await fetchUsers(); ``` Just return the array. There is no meaningful memory-management benefit in introducing a generator here. The additional abstraction might actually make the code harder to understand. **_Scenario B: You have 10 million records and need to process them sequentially._** A generator is a very good fit. ```javascript for await (const user of fetchUsers()) { await processUser(user); } ``` You avoid building an enormous array and can start processing early. **_Scenario C: You have 10 million records and need high throughput._** This is where a simple generator might not be enough. Suppose each record requires an independent network request. Sequential processing: ```javascript for await (const user of fetchUsers()) { await processUser(user); } ``` This might be memory-efficient but painfully slow. What you _absolutely_ shouldn't do is this: ```javascript await Promise.all( users.map(user => processUser(user)) ); ``` This can create millions of pending promises and retain millions of associated objects. Even if `users` originally came from a generator, converting it into a massive array or creating millions of pending promises defeats the original purpose. **A generator controls production. [Backpressure](https://www.geeksforgeeks.org/computer-networks/back-pressure-in-distributed-systems/) and [bounded concurrency control](https://www.geeksforgeeks.org/dbms/concurrency-control-in-dbms/) consumption.** You often need _both_. ## How does a programming language actually manage large data structures in memory? Now we're getting to the more fundamental question. Forget iterators for a moment. Suppose you write: ```python users = fetch_all_users() ``` Or: ```golang users := fetchAllUsers() ``` Or: ```javascript const users = await fetchAllUsers(); ``` What actually happens underneath? Regardless of the language, there are a few common stages: 1. **Allocation:** The runtime reserves memory for the data structure. 2. **Representation:** Data is stored as arrays, objects, pointers, buffers, etc. 3. **Access and mutation:** Your application reads, modifies and processes the data. 4. **Lifetime management:** Memory is reused or reclaimed when it is no longer needed. The interesting part is that different languages implement these stages differently. ### How Go manages memory Go uses a combination of stack allocation, heap allocation, escape analysis, and garbage collection. Consider: ```golang users := make([]User, 1000000) ``` A slice has a descriptor containing: - Pointer to its backing array. - Length. - Capacity. The backing array stores the actual elements contiguously. This is important because a slice is not itself the underlying array. For example: ```golang users := make([]int, 1000000) small := users[:10] ``` You might think `small` only occupies memory for 10 integers. But it still references the original backing array containing one million integers. Even if you discard `users`, keeping `small` alive can keep the entire backing array alive. This is a subtle memory-retention problem. A senior Go developer might solve it by copying the required elements into a smaller backing array: ```golang small := append([]int(nil), users[:10]...) ``` Now the new slice has its own smaller backing array. This is the kind of optimization that actually matters in production. ### How Python manages memory Python is interesting because its memory model differs quite a bit from Go. In CPython, the two important mechanisms are: 1. Reference counting. 2. Cyclic garbage collection. Consider: ```python users = [1, 2, 3, 4, 5] another_reference = users del users ``` Does the underlying list get destroyed? No. Because `another_reference` still points to it. Once the last reference disappears, CPython can generally reclaim the object through reference counting. Cyclic garbage collection handles objects that reference each other in cycles and would otherwise remain alive despite being unreachable from the application. There's another interesting detail. A Python list is not the same as a Go slice. A Python list stores references to Python objects in a dynamically sized array. Those objects generally live separately. So: ```python numbers = [1, 2, 3, 4, 5] ``` isn't necessarily five contiguous machine integers sitting inside the list's backing array. This introduces object and pointer overhead. For large numerical datasets, this is one reason developers use libraries such as NumPy. Instead of millions of individual Python integer objects, a NumPy array can store fixed-width numerical values in a contiguous memory buffer. For example: ```python import numpy as np numbers = np.arange(10_000_000) ``` This creates a compact numerical array rather than a Python list of individually allocated integer objects. And if you're processing millions of numerical values, the difference can be substantial. _**One qualification:** _reference counting describes CPython, not every Python implementation. ## When should we actually use generators? If I were establishing engineering guidelines for a backend team working in TypeScript, Python and Go, I'd use something like this: | Situation | Recommended approach | | --- | --- | | Small, bounded dataset | Array / List / Slice | | Large sequential dataset | Generator / Iterator | | Large database result | Cursor + incremental processing | | API with pagination | Async generator / iterator | | Large batch operations | Bounded batching | | CPU-heavy parallel processing | Bounded worker pool | | I/O-heavy concurrent processing | Bounded concurrency + backpressure | | Dataset larger than RAM | Streaming, disk-backed processing or distributed processing | The idea behind iterators and generators is surprisingly simple: **Don't make the consumer wait for all the data when it only needs the next piece of data.** But generators aren't a replacement for pagination, batching, database cursors, garbage collection or concurrency management. They complement these techniques by providing a reusable abstraction for lazy data production and consumption. My verdict: I would absolutely encourage generators in TypeScript and Python backend codebases, particularly for data-access layers, ETL jobs, large exports and transformation pipelines. Not because other memory-management techniques are inadequate, but because generators let us design APIs that don't force consumers to materialize entire collections unnecessarily. And the next time you see a function named `fetchAllSomething()`, maybe ask yourself: _Do I actually need all of it, or do I just need the next item?_ That’s it for this one, folks. Until Next Time, **Happy ~~Debugging ~~Coding👋** ## References - [TypeScript — Iterators and Generators](https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html) - [MDN — JavaScript Iteration Protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) - [Go 1.23 — Range Over Function Iterators](https://go.dev/doc/go1.23) - [Go — The iter Package](https://pkg.go.dev/iter) - [Python — Iterators and Generators](https://docs.python.org/3/howto/functional.html) - [Python — itertools](https://docs.python.org/3/library/itertools.html) *HTML:* https://adityakhare.com/articles/stop-fetching-everything-just-to-process-one-element-at-a-time *Markdown:* https://adityakhare.com/articles/stop-fetching-everything-just-to-process-one-element-at-a-time.md --- # I built my own Video Processing Pipeline using FFmpeg **URL:** https://adityakhare.com/articles/i-built-my-own-video-processing-infrastructure-using-ffmpeg **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2026-11-13T19:16:47.222Z **Updated:** 2026-11-18T10:33:03Z --- **Summary:** How I turned a screen recording application into a self-hosted video processing pipeline using FFmpeg, Node.js, Docker, Inngest, PostgreSQL and S3. I've been meaning to write about short tutorials like this for a while now but couldn't thinking that no one's going to be interested in tech problems I face everyday now that the answer is just an LLM call away. This changed with my recent [interaction with Flavio on X ](https://x.com/Aadi__khare/status/2118695075018575958?s=20)where he suggested that I should write even if it's only for myself. So here we go. ## Why and Where was it needed? Have you ever recorded a technical walkthrough, a bug reproduction, or a quick demo that you wanted to share over a meeting with a potential customer? My day job requires doing this on a daily basis. I've tried tools like [awesome screenshot ](https://www.awesomescreenshot.com/)but I decided to build my own for a fairly less complex app knowing that my data will be safe in my own hands rather than with a third-party app for which I would have to manage an additional subscription 😪. The idea (and initial UI) was plain and simple. You record a video, throw it somewhere in the cloud, generate a shareable link, and send it to whoever you want. That's how [**Snappit** ](https://snappit.adityakhare.com)came into existence. Snappit 📹 is a screen recording and video hosting application with a companion Chrome extension. You can record your screen, browser tab, or an individual window, upload the recording, play it back, and share it. The first iteration only saved and delivered the file as is, which for web recordings is the standard `.webm` format by default. So no hassle of video processing at all, In the later iterations, I wanted to change it and move to a more mature and universally accepted format for better UX. ## Why bother 🤷‍♂️? Ok, I know you're probably wondering why do you need to build and maintain your own video processing engine when you have a ton of third-party providers which do this for you by default like [cloudinary](https://cloudinary.com/documentation/javascript_video_transformations), [mux ](https://www.mux.com/docs/core/stream-video-files), [imagekit](https://imagekit.io/docs/video-transformation) etc. some cheaper than the others, all of them mostly running [ffmpeg ](https://www.ffmpeg.org/)under the hood. You can just pay them and move on. And typically, If I was working on a customer's project and have short deadlines and real-world stakes, I probably would. There are also open-source self-hosted alternatives like [Snapotter](https://snapotter.com/) and [Openinary](https://openinary.dev/) But as a 10x dev (me 🙂) famously said: > I want to get my hands dirty, break things, find out what broke and how, try to fix them my way so I can learn how to build it from scratch if and when it's needed. ![](https://cdn.sanity.io/images/r7i2kebp/production/0ea97091b2405d5e62234629fa415c472cd9ddf2-1500x1517.png) I wanted to understand what happens when multiple users start uploading massive video files and how will the server process it without bringing down the application. ## Why FFmpeg? If you've worked with images, you've probably used libraries like Sharp or ImageMagick. Video processing is a different beast. A video isn't just a file containing a sequence of images. It is a container that can hold multiple streams, including: - Video streams. - Audio streams. - Subtitles. - Metadata. - Chapters. Different devices and recording software produce different codecs, containers, resolutions, frame rates, and audio configurations. Trying to handle all these variations yourself is an excellent way to spend your weekend debugging media compatibility issues. FFmpeg solves this problem. FFmpeg is an open-source multimedia framework that provides command-line tools and libraries for manipulating audio and video. It basically is the **_backbone of modern file processing._** For Snappit, FFmpeg is responsible for converting uploaded recordings into a browser-friendly MP4 format. Why MP4? Because I want the resulting video to be playable across all media players without making every user worry about the codec used by the original recording software. ## Understanding the architecture 🗺️ Before touching ✋ the code, let's understand the architecture of our app. I use a monorepo (created using [turborepo](https://turborepo.dev)) with separate applications and shared packages. The important pieces are: - `apps/web`: Next.js application. - `apps/video-worker`: Long-running video processing service. - `packages`: Shared database, event, validation and storage functionality. - `extension`: Chrome extension responsible for browser-based recording. The web application runs on Vercel, whereas the video worker runs inside a Docker container on a VPS. Why separate them? Because web applications and video processing workloads have very different resource requirements. A typical API request might take a few milliseconds which can be easily run on vercel’s serverless functions. Video transcoding can take several minutes and consume substantial CPU and disk resources and generally require a dedicated long-running server. Mixing these workloads would be an unnecessary architectural constraint. ### The complete workflow ![](https://cdn.sanity.io/images/r7i2kebp/production/8045d1b4491bbaeb1fa578755281fc7a0c6ccc69-1639x1121.png) 1. The user records a video using the Chrome extension or web application. 2. The recording is buffered using IndexedDB and ArrayBuffers. 3. The thumbnail is generated using the initial frames of our recorded media stream 4. The video and thumbnail are uploaded and stored in object storage. 5. The application emits a `videoUploaded` event. 6. Inngest delivers the event to the connected video worker. 7. The worker downloads the original video from S3. 8. FFmpeg transcodes it into MP4. 9. The processed video is uploaded back to S3. 10. PostgreSQL is updated with the processing status. 11. The application can now serve the processed video for playback. Notice something important? **The web application never has to sit around waiting for FFmpeg to finish.** It simply initiates the processing workflow and moves on. That's the benefit of separating request handling from background workloads. **** #### **NOTE:** I also have a clean up Cron scheduled daily which deletes our video along with it’s metadata if they are more than a month old and also takes care of any ‘orphaned assets’ in our storage to keep them in sync with our Database. I use [n8n schedule trigger](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.scheduletrigger) for this but the code is pretty straight forward and you can implement this using any external service provider like [Vercel cron](https://vercel.com/docs/schedules/cron-jobs), [Inngest Scheduled Function Runs](https://www.inngest.com/docs/durable-execution/guides-and-advanced/events-and-triggers/schedules-and-delayed-starts) since we’re already using these services or just setup your own implementation using [node-cron](https://www.npmjs.com/package/node-cron) package on your server for maximum control. If you don’t want to write code, you can even ask your agent to create [scheduled tasks](https://learn.chatgpt.com/docs/automations) for this. Now let's get to the interesting part. _THE CODE_ ## The Pipeline Implementation Let's get our hands dirty. All the code is available on the remote [Repository](https://github.com/aadi-thedevguy/snappit). You can either surf through it or follow the development steps in the readme to follow along, run locally and actually experience how the flow works. Inside the repository, the FFmpeg implementation lives here: ```text apps/ video-worker/ src/ config.ts worker.ts services.ts repository.ts functions/ handlers.ts transcode-video-to-mp4.ts media/ ffmpeg.ts ``` Let's break it down. Before looking at the implementation, understand what FFmpeg actually does. A typical transcoding pipeline looks like this: ```text Input Video | v Demuxer | v Decoder | v Filter Graph | v Encoder | v Muxer | v Output Video ``` A demuxer extracts the individual streams from the input container. A decoder converts compressed video and audio into data that can be processed. A filter graph applies transformations such as resizing, cropping, or changing frame rates. An encoder compresses the resulting streams. Finally, a muxer packages the encoded streams into an output container. One important distinction: **Transcoding is not the same as changing a file extension.** Changing `video.mov` to `video.mp4` doesn't magically convert its underlying codecs. You need to ensure that the actual streams are compatible with your target format. Now let’s dive deep into different stages of our pipeline and see what each one does. ### 1. Understanding the FFmpeg command Let's look at the actual implementation in `apps/video-worker/src/media/ffmpeg.ts` The most important function is `mp4Arguments()`. Here's what it generates: ```typescript export function mp4Arguments( input: string, output: string ) { return [ "-protocol_whitelist", "file,pipe", "-i", input, "-map", "0:v:0", "-map", "0:a:0?", "-map_metadata", "-1", "-sn", "-dn", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p", "-threads", "2", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", output ]; } ``` Let's understand why each option exists. **_Input handling_** ```sh -protocol_whitelist file,pipe -i input.mp4 ``` The input is read from a local file. The protocol whitelist restricts which FFmpeg input protocols can be used. This is useful when processing untrusted uploaded media. **__** **_Stream selection_** ```sh -map 0:v:0 -map 0:a:0? ``` This is an interesting one. `0:v:0` means: - `0`: First input file. - `v`: Video stream. - `0`: First video stream. Similarly, `0:a:0?` selects the first audio stream. The question mark makes the audio mapping optional. Why? Because a screen recording might not contain audio. We don't want FFmpeg to fail simply because the input doesn't have an audio stream. **** **_Metadata and unwanted streams_** ```sh -map_metadata -1 -sn -dn ``` These options remove global metadata, subtitle streams, and data streams from the output. This keeps the generated output focused on the actual video and audio. **** **_Making dimensions compatible_** ```sh -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" ``` This is one of those tiny implementation details that saves you from annoying encoder errors. H.264 with the selected pixel format commonly expects even dimensions. If the input has an odd width or height, FFmpeg pads it to the next even dimension. For example: ```text Input: 1921 x 1081 Output: 1922 x 1082 ``` We aren't resizing the video. We're adding padding. **** **_Video encoding_** ```sh -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p -threads 2 ``` Here's what these options do: - `libx264`: H.264 video encoder. - `veryfast`: Encoding-speed versus compression-efficiency trade-off. - `crf 23`: Constant Rate Factor quality setting. - `yuv420p`: Widely compatible pixel format. - `threads 2`: Limits encoder thread usage. CRF is worth understanding. A lower CRF generally means better quality and larger output files. A higher CRF means more compression and potentially more visible quality loss. The useful thing about CRF is that it targets visual quality rather than a fixed output bitrate. **** **_Audio encoding_** ```sh -c:a aac -b:a 128k ``` We encode audio using AAC at 128 kbps. This gives us a widely supported audio format inside the MP4 container. **** **_Fast-start playback_** ```sh -movflags +faststart ``` This is another important option. MP4 files contain metadata describing their streams and media layout. The `faststart` option moves the MP4 metadata (the `moov` atom) towards the beginning of the file. This allows playback to begin without requiring the player to download the entire file first. For a video hosting application, this is particularly useful. ### 2. Executing FFmpeg safely from Node.js We don't want to construct a shell command by concatenating user-provided strings. Instead, Snappit uses `execa `to execute FFmpeg with an argument array. ```typescript export async function runFfmpeg( args: string[], config: MediaConfig, execute: typeof execa = execa ) { try { await execute( config.FFMPEG_PATH, [ "-nostdin", "-hide_banner", "-loglevel", "error", "-y", ...args ], { timeout: config.FFMPEG_TIMEOUT_MS, forceKillAfterDelay: 5000, maxBuffer: 1024 * 1024, stdout: "ignore" } ); } catch (error) { // Handle processing errors } } ``` A few things worth noting: 1. We execute FFmpeg directly instead of passing a constructed command through a shell. 2. `-nostdin` prevents FFmpeg from waiting for interactive input. 3. `-hide_banner` removes unnecessary startup information. 4. `-loglevel error` keeps logs manageable. 5. `-y` allows output files to be overwritten. 6. A timeout prevents a processing operation from running indefinitely. 7. `forceKillAfterDelay` gives the process a short grace period to terminate. There's also an important distinction in error handling. Invalid or corrupted media is treated as a non-retriable error. Infrastructure failures, such as timeouts or disk exhaustion, remain retriable. Why? Retrying a corrupted file twice isn't going to magically repair it. But a temporary infrastructure problem might resolve itself on the next attempt. This distinction becomes very important when you start processing videos asynchronously. ### 3. Managing temporary files One of the easiest ways to create a production problem with FFmpeg is to forget about temporary files. Imagine 100 users uploading videos simultaneously. If every job writes to the same directory or uses predictable filenames, you can end up with file collisions, accidental overwrites, or one job deleting another job's output. Snappit uses an isolated temporary directory for each processing attempt. ```typescript export async function withMediaDirectory( work: (directory: string) => Promise, parent = tmpdir() ) { await mkdir(parent, { recursive: true }); const directory = await mkdtemp( join(parent, "snappit-media-") ); try { return await work(directory); } finally { await rm(directory, { recursive: true, force: true }); } } ``` This is a very simple but effective pattern. Every processing attempt gets its own directory: ```text /tmp/snappit-media-a81x/ input output.mp4 /tmp/snappit-media-b92y/ input output.mp4 ``` When processing finishes, the directory is removed. The `finally` block ensures clean-up happens even when the processing operation throws an error. And here's an important **design decision:** temporary files belong to an individual processing step attempt, not to the entire durable workflow. This matters when a background job retries. Each attempt should start with a clean workspace. ## Building the background worker So far, we've seen how to convert a video. But who actually executes this conversion? We don't want our Next.js API route to start an FFmpeg process and wait for it to finish. Instead, we use a dedicated worker connected to [Inngest](https://www.inngest.com/). Think of Inngest as the event-driven orchestration layer. The web application emits an event, and the worker consumes it. ### Step 1: Registering the processing function Take a look at: `apps/video-worker/src/functions/transcode-video-to-mp4.ts` **The important part:** ```typescript return inngest.createFunction( { id: "transcode-video-to-mp4", name: "Transcode video to MP4", triggers: [videoUploaded], concurrency: { limit: 2 }, retries: 2, idempotency: "event.data.videoId", singleton: { key: "event.data.videoId", mode: "skip" }, onFailure: handlers.failure, }, handlers.process, ); } ``` Let's understand the configuration. **_Triggers_** `triggers: [videoUploaded]` The function executes when a video upload event is received. **_Concurrency_** `concurrency: { limit: 2 }` This limits the function's concurrent execution to two. Remember, video processing can be CPU-intensive. We don't want to start 50 FFmpeg processes on a machine with four CPU cores. **_Retries_** `retries: 2` The workflow can retry failed processing operations. **_Idempotency_** `idempotency: "event.data.videoId"` This prevents the same video from being independently processed multiple times for the same idempotency key. **_Singleton_** `singleton: { key: "event.data.videoId", mode: "skip" }` This adds another layer of protection against concurrent processing of the same video. These mechanisms solve different problems, and that's worth remembering when designing background jobs. ### Step 2: Claiming a video Before starting FFmpeg, we need to establish ownership of the processing job. Otherwise, imagine two worker executions attempting to process the same video. Both could download the original file, encode it, upload separate outputs, and race to update the database. Not ideal. Snappit handles this in `repository.ts`. The `claim()` method uses a PostgreSQL transaction and row-level locking: ```typescript const [existing] = await tx .select() .from(videos) .where(eq(videos.id, videoId)) .for("update"); ``` The `FOR UPDATE` clause locks the selected row for the duration of the transaction. The repository then checks: - Does the video exist? - Has the upload been finalized? - Is another processing run already handling it? - Has the video already been processed? If everything is valid, the video is marked as `processing`. This gives us database-level coordination in addition to the orchestration-level concurrency controls. ### Step 3: Processing the video The handler executes three major steps: ```text mark-processing | v transcode-and-upload-mp4 | v mark-ready ``` The actual rendering operation is delegated to the services layer. Here's the interesting part. The worker doesn't load the entire video into a JavaScript Buffer. It downloads the S3 object as a stream and writes it to disk. ```typescript await pipeline( body, limit, createWriteStream(input), { signal } ); ``` The `Transform` stream counts the number of bytes received and rejects files exceeding the configured maximum. The current implementation has a 500 MiB video limit. Once the download is complete: ```typescript await encode(input, output, config); ``` FFmpeg processes the local file. After processing, the worker obtains the output size and uploads the result using the AWS SDK's multipart upload functionality. ```typescript const upload = new Upload({ client: storage.client, params: { Bucket: storage.bucket, Key: getVideoObjectKey(processedKey), ContentType: PROCESSED_VIDEO_CONTENT_TYPE, ContentLength: size, Body: outputStream }, queueSize: 2, partSize: 8 * 1024 * 1024, leavePartsOnError: false }); await upload.done(); ``` Notice that the output is also streamed from disk rather than read completely into memory. This is important. We are keeping the memory footprint relatively predictable even when processing larger recordings. ### Step 4: Updating the processing status After a successful upload, the worker updates PostgreSQL DB. The status transitions are essentially: ```text uploading | v processing | v ready ``` If all retries fail: ```text processing | v failed ``` The repository also checks the processing run ID before updating the status. Why? Because a late failure from an older processing attempt should never overwrite the successful result of a newer attempt. This is a small implementation detail with a big impact on correctness. ## Running the worker using Docker Now we have a processing pipeline. But where does FFmpeg actually run? Inside a Docker container. The worker has its own Dockerfile: ```sh FROM node:22-bookworm-slim AS build ENV PNPM_HOME=/pnpm ENV PATH=$PNPM_HOME:$PATH RUN corepack enable \ && corepack prepare pnpm@10.28.0 --activate WORKDIR /repo COPY . . RUN pnpm install --frozen-lockfile \ --filter @snappit/video-worker... RUN pnpm --filter @snappit/video-worker build RUN pnpm --filter @snappit/video-worker \ deploy --prod /output FROM node:22-bookworm-slim AS runtime RUN apt-get update \ && apt-get install -y --no-install-recommends \ ffmpeg ca-certificates \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /var/tmp/snappit-media \ && chown node:node /var/tmp/snappit-media ENV NODE_ENV=production ENV FFMPEG_PATH=/usr/bin/ffmpeg ENV MEDIA_TEMP_DIRECTORY=/var/tmp/snappit-media WORKDIR /app COPY --from=build --chown=node:node /output ./ USER node CMD ["node", "dist/worker.js"] ``` A few architectural decisions here are worth appreciating. **_Multi-stage builds_** The build environment and runtime environment are separated. We don't need all the development dependencies in the production container. **_FFmpeg installation_** FFmpeg is installed in the runtime image, so the worker doesn't depend on FFmpeg being installed on the host machine. **_Non-root execution_** `USER node` The worker doesn't need to run as root. This reduces the impact of a potential compromise. This is just a best practice I do in every custom image I make **_Dedicated temporary directory_** ```sh ENV MEDIA_TEMP_DIRECTORY=/var/tmp/snappit-media ``` The worker has a predictable location for temporary media files. To build the worker image from the repository root: ```sh docker build \ -f apps/video-worker/Dockerfile \ -t snappit-video-worker . ``` Then run it with the worker's environment configuration: ```sh docker run -d \ --name snappit-video-worker \ --restart unless-stopped \ --env-file ./worker.env \ -p 8080:8080 \ snappit-video-worker ``` The worker exposes a `/ready` health endpoint. It reports readiness only after establishing its Inngest connection. One important distinction: this is not a standalone HTTP video-processing API. The worker establishes an outbound connection to Inngest and waits for events. The web application and the worker therefore don't need to communicate through a publicly exposed FFmpeg endpoint. ## How well does this scale 📈 Now for the question that matters when moving from a personal project to something people actually use. Does this architecture scale? The short answer: **Yes, horizontally, but with some important resource constraints.** Let's look at the bottlenecks. ### CPU FFmpeg transcoding is computationally expensive. In the current implementation, we use: `-preset veryfast -threads 2` The worker also has a configurable concurrency setting, defaulting to one worker connection slot. The processing function itself has a concurrency limit of two. These are two different concurrency controls, so the effective throughput depends on both. You can run multiple worker instances on separate machines and increase aggregate processing capacity. However, simply increasing concurrency on a small VPS is a good way to discover what CPU throttling feels like. ### Memory This is where the implementation makes some sensible choices. The input is downloaded using streams. The output is uploaded using streams. The video isn't loaded entirely into memory as one giant Buffer. That doesn't mean FFmpeg uses no memory. Decoding, encoding, filter buffers, and frame processing all consume memory. But the Node.js application avoids an unnecessary additional memory burden. ### Storage Temporary files are stored on local disk. This is efficient because FFmpeg works with local files rather than repeatedly fetching media from remote storage. However, local disk becomes a scaling constraint. If several large jobs execute simultaneously, they can consume substantial disk space. The temporary-directory cleanup helps, but production deployments still need adequate disk capacity and monitoring. ### Database PostgreSQL stores metadata and processing state. It doesn't store the actual video binaries. That's a good separation. Your database should be responsible for knowing which video belongs to whom, its processing status, and where its files live. Object storage should handle the actual media. ### Queue and worker scaling This is arguably the strongest part of the architecture. The web application and processing workers scale independently. For example: ```text Next.js Application | v Inngest Events | +----------+----------+ | | | v v v Worker 1 Worker 2 Worker 3 | | | v v v FFmpeg FFmpeg FFmpeg | | | +----------+----------+ | v S3 Storage ``` If processing demand increases, you can add worker instances without scaling your Next.js application. That's a much more flexible architecture than putting FFmpeg execution inside API routes. **One caveat:** the current implementation is a good foundation for moderate workloads, not proof of unlimited scale. The repository doesn't provide production throughput benchmarks, and actual capacity will depend on video duration, resolution, codec, CPU, disk performance, and worker configuration. ## What I did right There are several engineering decisions I particularly like. #### **1. Separation of responsibilities** The web application handles users, authentication, recording, and uploads. The worker handles CPU-intensive media processing. The storage layer handles media persistence. The database handles application state. Each component has a reasonably clear responsibility. #### **2. Streaming instead of loading everything into memory** This is important for large media files. Both input downloads and output uploads use streams. #### **3. Idempotent processing** Duplicate events and concurrent attempts are handled deliberately. This is essential when building reliable asynchronous systems. #### **4. Temporary file isolation** Each processing attempt gets its own directory. No shared filenames, no accidental interference between jobs. #### **5. Configurable processing** FFmpeg paths, timeouts, temporary directories, concurrency, and database connection settings are configurable. This makes deployment and tuning easier. #### **6. Docker-based deployment** FFmpeg dependencies are bundled into the worker environment. You don't have to manually maintain a matching FFmpeg installation on every machine. ## What I would improve next No architecture is perfect, and there are a few areas I'd improve as the application grows. ### 1. Add a proper processing priority system Not all videos are equally important. A user waiting for a 20-second recording shouldn't necessarily wait behind a 90-minute recording. I'd introduce different processing queues or priorities. For example: **High Priority**: Short recordings User-requested conversions Normal Priority: Regular uploads **Low Priority**: Thumbnail generation Background optimisations This improves perceived latency without necessarily increasing infrastructure costs. ### 2. Introduce adaptive concurrency Right now, concurrency is configurable, which is good. But a fixed concurrency limit doesn't necessarily account for the size of incoming videos. A 20 MB recording and a 450 MB recording can have drastically different processing requirements. I'd eventually consider resource-aware scheduling based on: - Available CPU. - Available RAM. - Available disk space. - Video duration. - Resolution. - Estimated processing complexity. The goal would be to avoid overloading the machine while maximising throughput. ### 3. Hardware acceleration The current implementation uses: `-c:v libx264` This is CPU-based encoding. For larger workloads, I'd explore hardware encoders such as: - NVIDIA NVENC. - Intel Quick Sync Video. - AMD AMF. For example, an NVIDIA-enabled FFmpeg build can use: `-c:v h264_nvenc` Hardware acceleration can significantly improve throughput for suitable workloads. However, it isn't automatically faster in every situation. I’ll benchmark before committing. ### 4. Generate thumbnails and multiple resolutions Our App is good enough. But a proper video hosting platform eventually needs more. I'd add: - Automatic thumbnail generation - Multiple resolution presets. - Preview clips. - Web-optimised playback variants. Currently, we already generate the thumbnail right there in the browser after our screen recording ends and before upload begins using the [Canvas Web API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). I’d want to this step to the server side as well. FFmpeg is very capable of clipping frames from our video stream and generating thumbnail from the initial frames. For example: ```sh ffmpeg -i input.mp4 \ -ss 00:00:05 \ -frames:v 1 \ -vf "scale=640:-1" \ thumbnail.jpg ``` This extracts a frame five seconds into the video and scales it to 640 pixels wide. I'd also consider generating 360p, 720p, and 1080p variants for adaptive playback. ### 5. Move towards HLS MP4 is great for straightforward playback. But if I eventually want adaptive bitrate streaming, I'd consider HLS. Instead of serving one large video file, we can generate a playlist and multiple smaller segments. ```sh ffmpeg -i input.mp4 \ -c:v libx264 \ -c:a aac \ -hls_time 6 \ -hls_playlist_type vod \ -hls_segment_filename "segment_%03d.ts" \ output.m3u8 ``` This is a simplified example, not a complete multi-bitrate HLS pipeline. The bigger idea is that the player can choose an appropriate quality based on network conditions. That's useful when users have different internet speeds or watch recordings on mobile networks. ### 6. Better observability > You can’t improve what you can’t measure Although our example project is for learning, if it ever moves to production or a Saas model, I'd want metrics for: - Average processing time. - Processing time by video duration and resolution. - Queue waiting time. - Failure rate. - Retry count. - CPU and memory usage. - Disk consumption. - Storage upload latency. I'd also introduce structured logs using services like [sentry](https://sentry.io), [posthog](https://posthog.com), [grafana loki](https://grafana.com/docs/loki/latest/) etc. with a consistent video ID and processing run ID that I can later run aggregations, visualization charts and make efficient business decisions depending on user actions and other analytics data. Knowing that a job failed is useful. Knowing why 15% of 4K recordings fail after 12 minutes is much more useful. ## So, should you build your own cloudinary? Let's look at the pros and cons of building your own video processing infrastructure: | Pros | Cons | | --- | --- | | Full control over processing | You own infrastructure maintenance | | No per-minute third-party transcoding dependency | CPU and storage costs | | Customisable FFmpeg pipelines | Codec compatibility is your responsibility | | Independent worker scaling | More operational complexity | | Own your media storage | Backups and lifecycle policies are your responsibility | | Can add custom processing features | Monitoring and debugging take effort | There is also an important economic consideration. Self-hosting doesn't automatically mean cheaper. If you have a handful of users uploading occasional recordings, a small VPS and object storage can be perfectly reasonable. If you suddenly have thousands of users uploading hours of 4K footage, your compute and storage bills can become substantial. At that point, you need to compare the total cost of ownership against managed video-processing services. The real advantage of self-hosting is control, flexibility, and the ability to build a processing pipeline around your exact requirements. #### Final thoughts Building snappit taught me something. An app as easy as this can go to unprecedented complexity if you let it be. Therefore it is necessary to have the vision of where you want to take a project. You need to be clear about which features deserve to be released in which iteration, how to make the decision between offloading to a third-party provider or ship and maintain your own from scratch. As for the video worker, I can keep evolving it into a more general-purpose media processing service, independent of any single application. The idea would be to expose a unified API where a client can upload an image or video, and once processing is complete, we notify them through a webhook. They then get a URL that can accept different parameters to retrieve the media in different formats, generate trimmed versions of videos, create multiple thumbnails, and perform other transformations, all through a single, consistent interface. Wouldn’t that be neat huh! But honestly, that would just be me reinventing the wheel. So Back to the original question: > Should you build your own video processing pipeline? ![](https://cdn.sanity.io/images/r7i2kebp/production/3e9259c3595dcf1e56bb3d564ca1a13854bdd622-200x200.gif) Just use one of the paid or open-source solutions mentioned in the article and move on. That’s it for this one folks. Until Next Time, **Happy ~~Debugging~~ Coding 👋** *HTML:* https://adityakhare.com/articles/i-built-my-own-video-processing-infrastructure-using-ffmpeg *Markdown:* https://adityakhare.com/articles/i-built-my-own-video-processing-infrastructure-using-ffmpeg.md --- # File Upload is broken, Let's fix it **URL:** https://adityakhare.com/articles/file-upload-is-broken-let-s-fix-it **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2026-11-03T13:09:26.597Z **Updated:** 2026-11-18T10:31:03Z --- **Summary:** Learn how file storage and retrieval work, where to store files, and how to build reliable uploads, downloads, processing, and cleanup into your application. **One of the most fundamental concepts of the web is sharing files over a network.** Everything you see on a web page is ultimately backed by data stored somewhere. Images, videos, documents, audio files, and even the HTML, CSS and JavaScript used to render the page, they're all fetched from somewhere. Some of the most widely used infrastructure services from companies like AWS, Cloudflare, and even self-hosted alternatives like MinIO are built around one simple requirement: **storing and serving files.** Today, we'll fix the ~~simple~~ surprisingly complex process of uploading a file to the internet. But before we get into the implementation, let's understand what we're actually dealing with. By the end of this article, you should be able to: - Understand how files are represented and transferred over the internet. - Decide whether a file belongs in your database, local file system or object storage. - Understand the difference between storing a file and delivering it to a user, including the associated network costs. - Implement file uploads and retrieval using different approaches, including pre-signed URLs, chunking and streaming. - Make an informed decision between managed cloud storage and running your own infrastructure. We'll use a typical SaaS application as our running example, where users can upload documents, profile pictures and videos. Let's get started. ## 1. The life of a file over the internet If you've never touched networking in college, let's do a quick refresher on some Computer Science. ### What is a file 🤔? A file is essentially a collection of bytes stored somewhere and identified by a name. Each byte is made up of 8 bits, and computers use these bytes to represent everything from plain text to images, videos and executable programs. There are hundreds of file formats, but from the perspective of how a computer stores and transfers them, we can start with two broad categories: 1. **Text files 🔡:** Files whose bytes are interpreted as characters using an encoding such as UTF-8. Examples include `.txt`, `.json`, `.csv` and `.md`. 2. **Binary files 👨‍💻:** Files whose bytes follow a format-specific structure. Examples include `.jpg`, `.png`, `.pdf`, `.zip` and `.mp4`. Now, here's an important distinction. A text file is also stored as bytes. The only difference is how software interprets those bytes. For example, consider a text file containing: `Hello` Its [UTF-8 representation](https://en.wikipedia.org/wiki/UTF-8) is: `48 65 6C 6C 6F` These are hexadecimal representations of the bytes that make up the word `Hello`. An image is also just a sequence of bytes, but instead of interpreting those bytes as characters, an image decoder follows the JPEG or PNG format to reconstruct the image. So, at the end of the day, both are just bytes. The format tells the software how to interpret them. **This is also why a file doesn't necessarily need to be converted into a string before it can be transferred or stored.** #### What is Base64? You might have encountered Base64 when working with images in APIs, data URLs or while debugging some weird-looking API response. Base64 is simply a way of representing arbitrary binary data using printable ASCII characters. For example, the word `Hello` can be represented as: ```text Hello → UTF-8 bytes 48 65 6C 6C 6F SGVsbG8= → Base64 representation ``` Why would we ever need this? Some systems or formats are designed to handle text rather than arbitrary binary data. Base64 gives us a way to represent those bytes using characters that such systems can handle. But there's a catch. **Base64 increases the size of the original data by roughly 33%.** So, converting every image or PDF to Base64 before uploading it is generally unnecessary when the underlying protocol already supports binary data. You can read more about the encoding itself in [MDN's explanation of Base64](https://developer.mozilla.org/en-US/docs/Glossary/Base64). ![](https://cdn.sanity.io/images/r7i2kebp/production/0a97a83b7cbb1c79adda12648ba15a4232af4881-1411x800.png) #### File extensions and MIME types Another thing worth understanding is the difference between a file extension and a MIME type. A file extension is simply a naming convention. For example: ```text profile-picture.jpg report.pdf notes.md ``` The `.jpg`, `.pdf` and `.md` parts tell us what kind of file we are probably dealing with. But they don't actually guarantee the contents of the file. I can rename an executable file to `vacation.jpg`, but that doesn't magically turn it into an image. 😅 This is where MIME types come in. A MIME type describes the nature and format of the data being transferred. Some common examples are** **`image/jpeg, image/png, application/pdf, text/plain, application/json, video/mp4` When a server sends a file over HTTP, it can specify its MIME type using the `Content-Type` header. For example: ```sh HTTP/1.1 200 OK Content-Type: image/jpeg Content-Length: 1048576 ``` This tells the browser that the response contains JPEG image data. **NOTE:** a MIME type provided by the client during upload is not proof that the file actually contains that type of data. We'll revisit this when discussing file validation. You can find a much more comprehensive explanation, along with a list of common MIME types, in [MDN's guide to MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types). ### How do files travel over the internet ✈️? Whenever your browser requests a web page, loads an image or submits a form, it communicates with a server using HTTP (or HTTPS). A simplified HTTP request for a file upload looks something like this: ```sh POST /api/files HTTP/1.1 Host: example.com Content-Type: multipart/form-data; boundary=xyz --xyz Content-Disposition: form-data; name="file"; filename="report.pdf" Content-Type: application/pdf --xyz-- ``` There are two things worth paying attention to here: 1. **Headers:** These carry metadata about the request, such as the content type, authentication information and other request properties. 2. **Body:** This is where the actual data being sent lives. Notice that the file is being sent as part of the request body. We aren't converting it to Base64 or doing anything fancy. HTTP supports different ways of sending data. One of the most common ones for browser-based file uploads is `multipart/form-data`. It allows us to send multiple fields in a single request, where each field can have its own content and headers. For example, we can send a file along with some additional metadata: `file = report.pdf user_id = 123 category = invoices` In JavaScript, the browser's `FormData` API handles the multipart formatting for us: ```javascript const formData = new FormData(); formData.append("file", selectedFile); formData.append("category", "invoices"); await fetch("/api/files", { method: "POST", body: formData }); ``` That's it. The browser takes care of constructing the multipart request, including the boundary used to separate individual fields. One small but important detail: **don't manually set the `Content-Type` header when sending a `FormData` object using `fetch`.** The browser needs to add the boundary parameter itself. You can read more about this in [MDN's FormData documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects). #### What about FTP and SFTP? HTTP isn't the only way to transfer files over a network. There are a few other protocols worth knowing about: - **HTTP/HTTPS:** _Transfers data between clients and servers_ - **FTP/SFTP: **_Traditional file transfer protocols_ Now, when should you use what? Let's say you're building a regular web application where users upload profile pictures and documents. HTTP/HTTPS is the obvious choice. Your browser already understands it, your backend exposes HTTP APIs, and your storage provider probably exposes an HTTP-based API as well. But imagine you're building an application that exchanges thousands of invoices with an external accounting company every night. The other company might provide an SFTP endpoint where you can upload and download files using SSH authentication. In that case, SFTP is a perfectly reasonable choice. A simple rule of 👍: - **Building a browser-based application or communicating with an API?** Use HTTPS. - **Exchanging files with an external system that exposes an SFTP endpoint?** Use SFTP. - **Working with a legacy integration that specifically requires FTPS?** Use FTPS. - **Considering plain FTP?** Avoid it for sensitive data because it doesn't encrypt the transfer. Also, SFTP isn't just FTP with a security layer added to it. It's a different protocol that operates over SSH. You can look at the [OpenSSH SFTP manual](https://man.openbsd.org/sftp) if you'd like to understand the actual tooling. > **💡 One thing to remember:** The size of a file doesn't automatically determine which transfer protocol you should use. HTTP and SFTP can both handle large files. Your integration requirements, authentication model and supported infrastructure should drive that decision. ![](https://cdn.sanity.io/images/r7i2kebp/production/3eb75302898bd99d4d2efbe35fa376e02b4befc9-1203x406.png) ### A file's first journey Let's put everything we've discussed together with a simple example. Imagine we're building a SaaS application where users can upload profile pictures. The journey looks something like this: 1. A user selects an image from their computer. 2. The browser reads the selected file using the File API. 3. The browser sends the file to our backend using an HTTP request. 4. The backend receives the file bytes and validates the request. 5. The backend needs to store the file somewhere. 6. Later, another user requests that image and our application needs to retrieve it. We've solved the transfer part, but there's still one important question left. **Where exactly should our backend store these bytes?** Let's look at our options. ## 2. Where should you store your files 🗄️? There are multiple ways of storing files, and each comes with its own trade-offs. You can store them directly in your database, on the same machine running your application, or use a dedicated storage system like AWS S3. Let's look at each option and, more importantly, understand when to pick what. ### Storing files inside your database 💾 This is probably the first thing that comes to mind when you're building an application with a database. Why not just create a column, insert the file and call it a day? Well, you can. But there are a few things to understand first. Most relational databases provide ways to store both text and binary data. For example, PostgreSQL supports: - `TEXT` for storing variable-length character data. - `BYTEA` for storing binary data. You can read more about [PostgreSQL's binary data types here](https://www.postgresql.org/docs/current/datatype-binary.html). Apart from PostgreSQL, almost all SQL/NoSQL Databases support binary data types. Let's say we're building an application where users can upload Markdown documents. We could simply store the contents of the Markdown file in a `TEXT` column: ```mysql CREATE TABLE documents ( id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); ``` This is a perfectly reasonable design. In fact, if your application needs to frequently read, update, search or version the contents of these documents, having them inside your database can make a lot of sense. What about binary files? We can use `BYTEA` to store the actual bytes: ```mysql CREATE TABLE attachments ( id SERIAL PRIMARY KEY, filename TEXT NOT NULL, content BYTEA NOT NULL ); ``` Notice that we're storing raw binary data here, not a Base64-encoded string. So, should we just store every file in the database? Not necessarily. **The problem with storing files in your database isn't that databases cannot handle binary data. It's that they're usually optimized to solve a different problem.** As your application grows, storing large files directly in the database can introduce a few challenges: 1. Database size increases considerably. 2. Backups and restores become heavier. 3. Replication has to deal with larger amounts of data. 4. Large binary reads and writes can compete with your normal application queries. 5. Serving files through your database can introduce unnecessary load on your primary application infrastructure. This doesn't mean you should never store files in a database. A small Markdown document that is part of your application's core data model is a very different problem from a 500 MB video uploaded by a user. **When should you choose database storage?** - When the file is actually application data that you need to query or modify. - When it needs to participate in the same transaction as other database records. - When you have relatively small binary files and a good reason to keep them alongside your application data. - When your application benefits from database-level consistency and access control. And here's an important distinction: a file extension or size alone shouldn't determine where it belongs. A Markdown document can be stored in PostgreSQL as `TEXT` if it's part of your application's content model. But if users are uploading Markdown files as independent attachments, object storage might be a better fit. ### Storing files on your application server Another straightforward approach is to store files directly on the machine running your application. Most programming languages provide APIs to read and write files to the local filesystem. In Node.js, for example: ```javascript import fs from "node:fs/promises"; await fs.writeFile( "./uploads/report.pdf", fileBuffer ); ``` This writes the file directly to the filesystem of the machine running your Node.js process. Simple enough, right? For a small application running on a single server, this can work perfectly fine. But now imagine that your application starts receiving more traffic. You decide to scale horizontally and run three application instances behind a load balancer. ```text Load Balancer | ------------------- | | | App 1 App 2 App 3 | | | Disk Disk Disk ``` Now consider this scenario: 1. A user uploads a profile picture. 2. The load balancer routes the request to App 1. 3. App 1 stores the file in its local `uploads` directory. 4. A subsequent request gets routed to App 2. 5. App 2 tries to read the same file. And... the file isn't there. 😐 That's because each application instance has its own filesystem. You could introduce a shared filesystem or synchronize the files between machines, but now you're adding another piece of infrastructure to maintain. There's also the issue of persistent vs ephemeral storage. For example, when running applications inside containers, data written to the container's writable filesystem may disappear when the container is replaced. You can solve this using persistent volumes, but that doesn't automatically solve the problem of sharing files between multiple instances. **When should you choose local filesystem storage?** - Small applications running on a single machine. - Temporary files created during processing. - Files that are generated and consumed by the same worker. - Applications where the files don't need to survive the lifecycle of the application instance, or where persistence is explicitly managed. For most applications that expect to scale horizontally, I'd avoid treating the local filesystem as the primary storage for user-uploaded files. ### Object storage Now we're getting to the most popular form of file storage used in modern apps. Object storage is a storage model specifically designed to store and retrieve large amounts of unstructured data. Instead of thinking in terms of files and directories, think of objects stored inside containers called buckets. An object generally consists of: - **Key:** The identifier used to locate the object. - **Value:** The actual bytes of the file. - **Metadata:** Additional information describing the object. For example, we could have a bucket called `user-uploads` containing an object with this key: `users/123/profile-picture.jpg` The object key is what we use to identify and retrieve the file. Notice that the key looks like a directory structure. But object storage generally doesn't behave like a traditional filesystem. Those slash-separated names are object keys, not necessarily actual directories. The reason object storage is so popular for modern applications is that it separates file storage from the application itself. Your application doesn't need to worry about which physical machine holds the file or how many application instances are running. It simply communicates with the storage service using its API. Your application can upload, retrieve or delete objects without having to manage the underlying storage hardware. You can also store additional metadata alongside objects, configure access policies, enable versioning and introduce lifecycle rules. For example, AWS S3 provides all of these capabilities through its object storage APIs. Its [official object storage documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingObjects.html) is a good place to explore those features. **When should you choose object storage?** - User-uploaded images, PDFs and documents. - Audio and video files. - Large files that have an independent lifecycle from your application records. - Applications running multiple instances. - Applications that need to serve files independently of their application servers. For a typical SaaS application, this is generally where I'd start. Keep your application data and file metadata in the database, and store the actual file bytes in object storage. For example: ```text PostgreSQL -------------------------------- id: 123 filename: profile-picture.jpg object_key: users/123/profile-picture.jpg content_type: image/jpeg size: 1048576 ``` ```text Object Storage -------------------------------- Bucket: user-uploads Key: users/123/profile-picture.jpg Value: ``` This way, the database knows _about_ the file, but it doesn't have to store the file itself. Pretty neat, right? It's only con is that you have to have good systems in place to keep your remote bucket in sync with your Database so you don't run into orphan assets or inconsistent DB records. ### What about NAS, block storage and other systems? There are a few more storage technologies worth knowing about, but we don't need to get into their internals here. **NAS (Network Attached Storage)** A NAS is essentially a machine that provides shared storage over a network. It's useful when multiple machines need access to the same files through a shared filesystem. You might encounter it in self-hosted environments or applications that already depend on shared network storage. **Block storage** Think of this as a virtual disk that you attach to a server. Cloud providers offer block storage services that behave much like disks attached to physical machines. For example, AWS EBS is commonly used to provide persistent block storage to EC2 instances. You generally use this underneath databases, application servers or filesystems rather than as a direct replacement for an object storage API. **Distributed filesystems** These provide a shared filesystem interface across multiple machines. They're useful for specialized workloads where applications require filesystem semantics but the underlying storage needs to span multiple nodes. The important thing is that these technologies exist, and each solves a slightly different problem. **For most of the applications, we generally don't use these.** OK, So fare we've looked at the different places our files can live, and we have a reasonable idea of what to choose for different application requirements. But storing a file is only half the problem. **What happens when somebody wants to download it? And more importantly, who pays for moving those bytes across the network?** Let's talk about that next. ## 3. Retrieving files isn't free So far, we've discussed where to store files. But there's another part of the equation that developers often overlook: **retrieving and delivering those files.** Storing a 100 GB video library is one thing. Serving those videos to 10,000 users every day is an entirely different problem. Let's understand why. ### How does an application retrieve a file? The retrieval process depends on where we've stored the file. If we're storing a document in PostgreSQL, our application queries the database and receives the contents of the corresponding `TEXT` or `BYTEA` column. If we're using a local filesystem, the application reads the file from its path. And if we're using object storage, the application makes a GET request to the storage provider using the bucket and object key. Let's take our SaaS application example again and take the case where our database stores the metadata of the file, while object storage holds its actual bytes. That means a retrieval request generally involves both systems. Imagine a user requests an invoice. Our application first needs to: 1. Identify the file the user is requesting. 2. Fetch its database record. 3. Verify that the user is authorized to access it. 4. Check whether the file is in a state that allows retrieval. 5. Retrieve the actual bytes from storage or generate a URL that allows the user to retrieve them. Notice that we're not blindly requesting an object from S3 using whatever key the browser sends us. The database tells us which object belongs to the requested file, who owns it and whether it's available. Imagine a user wants to download an invoice. We have two ways of handling this. #### 1. Server-mediated retrieval 🚦✋ The browser requests the invoice from our backend. Our backend checks whether the user is authorized to access it, fetches the file from object storage and returns it to the browser. ```text Browser | v Backend API | +------> PostgreSQL | Verify ownership | Check file status | +------> Object Storage | Fetch object | v Browser receives file ``` The application server handles the entire transfer. This gives us greater control over the response. We can transform the file, add watermarks, audit the download or perform additional checks before returning it. But there's a downside. Every byte downloaded by the user also passes through our application infrastructure. Imagine 1,000 users downloading a 100 MB file. That's approximately 100 GB of data that our backend has to handle, in addition to its normal API traffic. #### 2. Direct retrieval 📩 using a pre-signed URL Another option is to let the backend authorize the request and generate a temporary URL that allows the browser to retrieve the file directly. ``` Browser → Backend (request file) | v PostgreSQL Check ownership Check file status | v Backend | Generate signed URL | v Browser ← Pre-signed URL | v Object Storage | v Browser receives file ``` Here, the backend is responsible for access control, but the actual transfer happens between the browser and object storage. This is particularly useful when dealing with large files or applications serving a lot of user-generated content. ![](https://cdn.sanity.io/images/r7i2kebp/production/ac165bafea6915793b823c072a41408fc62c3500-2064x812.png) **When should you choose what?** - **Server-mediated retrieval:** When the application needs to inspect, modify, transform or audit the file before delivering it. - **Direct retrieval:** When the file can be served as-is and you want to keep bulk data transfer away from your application servers. One thing worth remembering: direct retrieval doesn't mean public retrieval. We can keep our bucket private and authorize each download using a [pre-signed URL](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html?utm_source=chatgpt.com). ### Understanding the cost 💰 of retrieval Now comes the interesting part. Cloud storage providers generally don't charge you for just one thing. Depending on the provider and storage class, your bill can contain several components: - **Storage:** How much data you're storing and for how long. - **Requests:** PUT, GET, LIST and other API operations. - **Data retrieval:** Some infrequent-access and archive storage classes charge additional retrieval fees. - **Data transfer:** The amount of data leaving the provider's network. - **Additional services:** CDN delivery, replication, processing and other infrastructure. The last two deserve particular attention. Let's say we have an application with: - 100 GB of stored user files. - 10,000 active users. - Each user downloads an average of 100 MB every month. Our monthly data transfer would be: 10,000 users × 100 MB = 1,000,000 MB ≈ 1,000 GB ≈ 1 TB Notice something? **We're storing 100 GB but delivering approximately 1 TB every month.** That's 10 times the amount of data we're storing. And this isn't even an unusually large application. The actual bill will depend on the provider, region, storage class, request volume and any free allowances or negotiated discounts. For example, AWS S3 separates storage, request, retrieval and data-transfer pricing. Cloudflare R2 currently advertises no internet-egress charge, although storage, operations and certain retrieval charges still apply. You can check their pricing models here: - [AWS S3 Pricing](https://aws.amazon.com/s3/pricing/) - [Cloudflare R2 Pricing](https://developers.cloudflare.com/r2/pricing/) I'm not going to hardcode pricing into this article because it changes frequently. Always calculate using your expected upload volume, stored data, downloads and request patterns. ### What is a CDN and when do you need one 🤷? Let's introduce one more piece of infrastructure that can significantly improve file delivery: a Content Delivery Network (CDN). A CDN is a network of geographically distributed servers that cache and deliver content closer to the user requesting it. Imagine our application stores profile pictures in an object storage bucket located in the US. A user sitting in India requests one of these images. Without a CDN, the request might travel all the way to our storage origin in the US every time. With a CDN, the journey looks a little different. The first time the image is requested, the CDN's edge server might not have it cached. This is called a **cache miss**. The CDN fetches the image from the origin, returns it to the user and, when the caching rules allow, stores a copy at the edge. The next time another user requests the same image from that edge location, the CDN can serve it directly. This is called a **cache hit**. ![](https://cdn.sanity.io/images/r7i2kebp/production/b72b299abab110c9cc92e159d2e80c6ae67f0433-1398x480.png) This helps reduce repeated requests to our origin storage and can improve latency for users located far away from it. CDNs are particularly useful for: - Profile pictures and other static assets. - Publicly accessible documents. - Images and videos. - Files that are requested repeatedly by multiple users. But there's one catch. You need to configure caching correctly. For example, you don't want a CDN accidentally serving one user's private invoice to another user just because both requests point to the same URL. For private content, use appropriate authorization mechanisms such as signed URLs or signed cookies, and make sure the CDN's cache policy respects the privacy requirements of the content. Also, a CDN doesn't magically make bandwidth free. You're still paying for delivery according to your provider's pricing model, even though you might be reducing requests to the original storage. **When should you introduce a CDN?** - Low traffic and mostly private files? Direct object storage delivery might be enough. - Frequently accessed public assets? A CDN is worth considering. - Large media libraries with users distributed geographically? A CDN can become an important part of the architecture. - Private user-specific documents? Use proper access controls before optimizing cache hits. ## 4. Implementing file upload and retrieval We've covered quite a bit so far. We know what files are, how they're transferred, where to store them and what happens when users retrieve them. Now let's put everything together. For this section, we'll use: - PostgreSQL for file metadata and application-level state. - [Prisma ORM](https://prisma.io) for our TypeScript implementation. - [GORM](https://github.com/go-gorm/gorm) for our Go implementation. - S3-compatible object storage for the actual file bytes. The tech decisions are based on my domain expertise and you can find similar design implementations across most language and frameworks. Also, there's one architectural principle I want you to keep in mind throughout this section: **The database and object storage are two independent systems. We cannot wrap operations on both inside one ordinary database transaction.** This means we have to explicitly design for failures, retries and reconciliation. ### Designing the file lifecycle 🔁 Before writing any upload code, let's decide what information our application needs to track. We don't want a database record to simply say that a file exists. We want it to tell us exactly where that file is in its lifecycle. Let's introduce a `File` model with the following fields: - `id`: Unique identifier for the file. - `ownerId`: User who owns the file. - `originalName`: Original filename provided by the user. - `bucket`: Object storage bucket. - `objectKey`: Unique key used to identify the object. - `contentType`: Expected MIME type. - `sizeBytes`: Actual size of the uploaded file. - `checksum`: Optional checksum used to verify file integrity. - `status`: Current state of the file. - `createdAt`: When the upload was initiated. - `updatedAt`: Last time the record was updated. - `deletedAt`: When the file was marked for deletion. For the status, we'll use the following lifecycle states: - **PENDING_UPLOAD:** The database record exists, but the object hasn't been verified in storage. - **UPLOADED:** The object exists in storage and has passed our initial upload verification. - **PROCESSING:** The file is being scanned, converted or otherwise processed. - **READY:** The file is available for retrieval. - **DELETE_PENDING:** The file has been marked for deletion, but the object might still exist. - **DELETED:** The object has been deleted and the database reflects that. - **FAILED:** The upload or processing operation failed and needs investigation, retry or cleanup. Notice that we're not marking a file as `READY` immediately after generating a pre-signed URL. Generating an upload URL only means that we've authorized an upload. It doesn't mean the user actually uploaded anything. This distinction is extremely important. ### Modelling files using Prisma Let's start with our JavaScript application. We'll use Prisma ORM to define the file model. ```typescript enum FileStatus { PENDING_UPLOAD UPLOADED PROCESSING READY DELETE_PENDING DELETED FAILED } model File { id String @id @default(uuid()) ownerId String originalName String bucket String objectKey String @unique contentType String sizeBytes BigInt? checksum String? status FileStatus @default(PENDING_UPLOAD) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? @@index([ownerId, status]) @@index([status, createdAt]) } ``` A few things worth pointing out: - `objectKey` is unique because we don't want two database records accidentally pointing to the same object. - `sizeBytes` is nullable because we don't know the actual uploaded size when the upload is first initiated. - `status` allows us to track the file lifecycle. - The indexes help us find files belonging to a user and identify files that have been stuck in a particular state. In a real application, `ownerId` would generally be a relation to your existing `User` model, with a foreign key and an appropriate deletion policy. We should also have a separate `OutboxEvent` model for reliable background processing, which we'll introduce shortly. ### Modelling files using GORM For our Go application, we'll use GORM. GORM is one of the most widely adopted ORM libraries in the Go ecosystem. It supports struct-based models, associations, transactions, hooks and migrations. Here's how our model looks: ```golang type FileStatus string const ( FilePendingUpload FileStatus = "PENDING_UPLOAD" FileUploaded FileStatus = "UPLOADED" FileProcessing FileStatus = "PROCESSING" FileReady FileStatus = "READY" FileDeletePending FileStatus = "DELETE_PENDING" FileDeleted FileStatus = "DELETED" FileFailed FileStatus = "FAILED" ) type File struct { ID string `gorm:"type:uuid;primaryKey"` OwnerID string `gorm:"type:uuid;not null;index"` OriginalName string `gorm:"not null"` Bucket string `gorm:"not null"` ObjectKey string `gorm:"not null;uniqueIndex"` ContentType string `gorm:"not null"` SizeBytes *int64 Checksum *string Status FileStatus `gorm:"type:varchar(30);not null;index"` CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` } ``` We're keeping the same fields and life cycle in both implementations. This is important because the ORM is only an abstraction over our database. The underlying data model and the consistency requirements don't change just because we're using Go instead of TypeScript. ### The upload process: database first, storage second Let's walk through an actual upload. Imagine a user wants to upload `invoice.pdf`. The browser first calls our backend to request an upload URL. Before generating that URL, the backend should: 1. Authenticate the user. 2. Validate the requested filename, content type and expected file size. 3. Generate a unique object key. 4. Create a database record with `PENDING_UPLOAD`. 5. Generate a pre-signed PUT URL. 6. Return the file ID, upload URL and required headers to the browser. Notice the order. **We're creating the database record before the actual file is uploaded.** Why? Because we want to know that an upload was initiated, even if the user closes their browser halfway through. If we only create the database record after the upload, we have no reliable record of uploads that were started but never completed. Our object key should also be generated by the backend rather than accepting an arbitrary storage path from the client. For example: ```text users/456/files/550e8400-e29b-41d4-a716-446655440000 ``` We can keep the original filename in PostgreSQL while using a unique, server-generated object key in storage. This avoids filename collisions and prevents users from choosing paths that could overwrite other objects. Let's implement the first part using Prisma. ```typescript import { randomUUID } from "node:crypto"; import { PrismaClient, FileStatus } from "@prisma/client"; const prisma = new PrismaClient(); async function initiateUpload( userId: string, originalName: string, contentType: string ) { const allowedTypes = new Set([ "image/jpeg", "image/png", "application/pdf" ]); if (!allowedTypes.has(contentType)) { throw new Error("Unsupported file type"); } const fileId = randomUUID(); const objectKey = `users/${userId}/files/${fileId}`; const file = await prisma.file.create({ data: { id: fileId, ownerId: userId, originalName, bucket: "user-uploads", objectKey, contentType, status: FileStatus.PENDING_UPLOAD } }); const command = new PutObjectCommand({ Bucket: file.bucket, Key: file.objectKey, ContentType: file.contentType }); const uploadUrl = await getSignedUrl( s3, command, { expiresIn: 300 } ); return { fileId: file.id, uploadUrl, method: "PUT", headers: { "Content-Type": file.contentType } }; } ``` For Go, the same operation can be implemented using GORM: ```golang func initiateUpload( db *gorm.DB, userID string, originalName string, contentType string, ) (*File, error) { fileID := uuid.NewString() objectKey := fmt.Sprintf( "users/%s/files/%s", userID, fileID, ) file := File{ ID: fileID, OwnerID: userID, OriginalName: originalName, Bucket: "user-uploads", ObjectKey: objectKey, ContentType: contentType, Status: FilePendingUpload, } if err := db.Create(&file).Error; err != nil { return nil, err } return &file, nil } ``` The function creates the database record. The S3 pre-signed URL is generated separately using the AWS SDK for Go. One thing to notice: we're not opening a database transaction around the S3 request. There's no reason to keep a database transaction open while waiting for an external service. The database record has already been committed. If URL generation fails, we can mark the upload as failed or allow the pending record to expire and be cleaned up later. ### The browser uploads the file Once the backend returns the pre-signed URL, the browser can upload the file directly. ```javascript const response = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": file.type }, body: file }); if (!response.ok) { throw new Error("Upload failed"); } ``` At this point, the object might exist in storage, but our database still says `PENDING_UPLOAD`. And that's intentional. The browser is not responsible for deciding whether our application considers the file ready. Instead, it should notify our backend that the upload has completed. ### Verifying the upload and updating the database After the browser finishes uploading, it calls a completion endpoint: ```text POST /api/files/{fileId}/complete ``` Our backend now needs to verify that the object actually exists. For S3, we can use `HeadObject`. This retrieves object metadata without downloading the actual file bytes. We can verify: - Whether the object exists. - Its actual size. - Its content type. - Its checksum, if configured and available. We should never blindly trust the size or content type sent by the browser. For example, the client might claim that it uploaded a 1 MB PDF, while the actual object is 500 MB or contains something entirely different. After verifying the object, we update the database. But there's another important detail. What if the object upload succeeds and the `HeadObject` request succeeds, but our database update fails? The object exists, but the database still says `PENDING_UPLOAD`. This is one of the reasons we introduced explicit lifecycle states. We can retry the verification and update operation without asking the user to upload the file again. For example, using Prisma: ```typescript const file = await prisma.file.findFirst({ where: { id: fileId, ownerId: userId, status: FileStatus.PENDING_UPLOAD } }); if (!file) { throw new Error("Invalid upload"); } // Verify object existence and metadata using HeadObject. const head = await s3.send( new HeadObjectCommand({ Bucket: file.bucket, Key: file.objectKey }) ); if (head.ContentLength == null) { throw new Error("Unable to verify file size"); } await prisma.file.updateMany({ where: { id: file.id, ownerId: userId, status: FileStatus.PENDING_UPLOAD }, data: { sizeBytes: BigInt(head.ContentLength), status: FileStatus.UPLOADED } }); ``` This is a simplified verification step. In production, we should also compare the expected size, enforce size limits, validate the actual content and verify the checksum when available. Also, notice that we're using `updateMany` with the expected current status. This is a conditional state transition. If another request has already changed the record, we don't blindly overwrite its new state. For a production implementation, check that exactly one row was updated and handle duplicate completion requests idempotently. ### Processing files before making them available An uploaded file isn't necessarily ready to be served. Depending on our application, we might need to: - Scan it for malware. - Validate its actual file signature. - Generate image thumbnails. - Extract PDF text. - Transcode a video. - Generate HLS playlists and video segments. We don't want the browser waiting for all these operations to finish inside the upload request. Instead, we can publish a background job after the upload has been verified. The worker processes the file and eventually changes its state to `READY`. Only files in the `READY` state should be available for normal retrieval. If processing fails, the worker can retry or mark the file as `FAILED`, depending on the error. And this brings us to another important production concern. ### Keeping the database and object storage in sync Remember when I said that our database and object storage don't share a transaction? Let's look at what that actually means. Imagine we perform these two operations: 1. Upload file to S3 2. Insert file metadata into PostgreSQL What happens if the upload succeeds but the database insert fails? We have an object in S3 that our application doesn't know about. Now reverse the order: 1. Insert file metadata into PostgreSQL 2. Upload file to S3 What happens if the database insert succeeds but the upload fails? We have a database record pointing to an object that doesn't exist. Both are valid failure scenarios. This is commonly known as a **dual-write problem**: one business operation requires writing to two independent systems, but we don't have a single atomic transaction covering both. You can read more about the [Transactional Outbox pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html), which addresses a related reliability problem. #### Using the Transactional Outbox pattern One way to make our workflow more reliable is to introduce an outbox table. Instead of updating the database and publishing a background job as two independent operations, we create both records inside the same database transaction. For example, after verifying the uploaded object, we want to: 1. Change the file status to `UPLOADED`. 2. Create an event asking a worker to process the file. Both operations happen in one PostgreSQL transaction. Here's the Prisma example: ```typescript await prisma.$transaction(async (tx) => { await tx.file.update({ where: { id: fileId }, data: { status: FileStatus.UPLOADED, sizeBytes: BigInt(actualSize) } }); await tx.outboxEvent.create({ data: { type: "FILE_UPLOADED", aggregateId: fileId, payload: { fileId } } }); }); ``` Our `OutboxEvent` model might contain: - `id`: Unique event ID. - `type`: Event type, such as `FILE_UPLOADED`. - `aggregateId`: ID of the file associated with the event. - `payload`: Event data. - `createdAt`: Event creation timestamp. - `processedAt`: When the event was successfully handled. - `attempts`: Number of processing attempts. A separate worker continuously polls for unprocessed events, publishes them to our job queue and marks them as processed. For GORM, the same transaction looks like this: ```golang err := db.Transaction(func(tx *gorm.DB) error { if err := tx.Model(&File{}). Where( "id = ? AND status = ?", fileID, FilePendingUpload, ). Updates(map[string]interface{}{ "status": FileUploaded, "size_bytes": actualSize, }).Error; err != nil { return err } event := OutboxEvent{ ID: uuid.NewString(), Type: "FILE_UPLOADED", AggregateID: fileID, Payload: payload, } if err := tx.Create(&event).Error; err != nil { return err } return nil }) ``` If either database operation fails, the entire transaction rolls back. Now our worker can safely pick up the event later. One important thing: the worker should be idempotent. This means that processing the same event twice shouldn't corrupt the file or create duplicate processing jobs. Also, don't assume that marking an event as processed and publishing it to a message broker are automatically atomic. A worker can crash after publishing but before updating the outbox row. That's why we generally design this pattern around **at-least-once delivery**, with idempotent consumers. The outbox solves reliable communication between our database and background processing system. It doesn't magically make PostgreSQL and S3 one transactional system. For our file upload workflow, we still need retries and reconciliation for failures involving object storage. ### Retrieving files using the database as the source of truth Now that we've built the upload life cycle, retrieval becomes much simpler. The browser shouldn't send an arbitrary object key and expect the backend to return whatever it points to. Instead, the browser requests a file using its database ID. For example: ```text GET /api/files/550e8400-e29b-41d4-a716-446655440000/download ``` Our backend: 1. Finds the file record using its ID. 2. Checks that the authenticated user has permission to access it. 3. Checks that the file status is `READY`. 4. Retrieves the bucket and object key from the database. 5. Generates a pre-signed GET URL. 6. Returns the URL to the browser. The Prisma implementation is straightforward: ```typescript async function createDownloadUrl( fileId: string, userId: string ) { const file = await prisma.file.findFirst({ where: { id: fileId, ownerId: userId, status: FileStatus.READY } }); if (!file) { throw new Error("File not found"); } const command = new GetObjectCommand({ Bucket: file.bucket, Key: file.objectKey }); return getSignedUrl( s3, command, { expiresIn: 300 } ); } ``` Notice that we're not accepting the object key from the client. The database provides the actual storage location, and the application enforces ownership and file availability before generating the URL. For files shared with other users, replace the simple `ownerId` check with your application's actual authorization rules. For example, a document might be accessible to users belonging to the same organization, even if they weren't the ones who uploaded it. **When should you retrieve using a database record?** Pretty much whenever you're building an application where files belong to users, organizations, projects or other application entities. The database should determine whether the file is accessible. Object storage should only be responsible for returning its bytes. ### Deleting files without leaving orphaned assets Now comes the part that is surprisingly easy to get wrong. Deleting a file is not just a matter of calling `DeleteObject` and removing a database row. Remember, we have two independent systems. Imagine we do this: 1. Delete file record from PostgreSQL 2. Delete object from S3 If the S3 request fails, we've lost the database record but the object is still consuming storage. We've created an orphaned asset. What if we reverse the order? 1. Delete object from S3 2. Delete file record from PostgreSQL If the database operation fails, we have a database record pointing to an object that no longer exists. Neither approach is ideal. Instead, we'll use a deletion lifecycle. **Step 1: Mark the file for deletion** First, update the database record: ```typescript await prisma.file.updateMany({ where: { id: fileId, ownerId: userId, status: FileStatus.READY }, data: { status: FileStatus.DELETE_PENDING, deletedAt: new Date() } }); ``` The file is now unavailable for normal retrieval, but its database record still exists. **Step 2: Create a deletion event** In the same database transaction, create an outbox event: ```typescript await prisma.$transaction(async (tx) => { const result = await tx.file.updateMany({ where: { id: fileId, ownerId: userId, status: FileStatus.READY }, data: { status: FileStatus.DELETE_PENDING, deletedAt: new Date() } }); if (result.count !== 1) { throw new Error("File cannot be deleted"); } await tx.outboxEvent.create({ data: { type: "FILE_DELETE_REQUESTED", aggregateId: fileId, payload: { fileId } } }); }); ``` Now we have a durable record of the deletion request. **Step 3: Let a background worker delete the object** The worker consumes the event, retrieves the file's object key and calls the storage provider's delete API. If the deletion succeeds, it updates the database status to `DELETED`. If the S3 request fails, the worker retries the operation. Deleting the same object again is generally safe for this workflow, which makes retries much easier. **Step 4: Retain or eventually purge the database record** We don't necessarily need to physically delete the database record immediately. Keeping a tombstone or soft-deleted record helps with: - Audit trails. - Retry operations. - Troubleshooting. - Understanding who deleted a file and when. - Preventing accidental reuse of identifiers. We can permanently purge old metadata records later, according to our retention policy. For Go, the deletion request follows the same pattern using `db.Transaction`, updating the file state and inserting an `OutboxEvent` in one transaction. The worker can then use the AWS SDK to delete the object and update the record. ### What happens to orphaned files? Even with a well-designed upload and deletion workflow, failures can still leave our database and object storage out of sync. For example: - A user uploads a file but closes the browser before calling the completion endpoint. - An upload succeeds but the database update fails. - A worker crashes after deleting an object but before updating the database. - A deployment interrupts a processing job. - An administrator manually deletes an object from the storage console. We need a reconciliation process to catch these situations. I'd introduce two periodic background jobs. **1\. Database-to-storage reconciliation** Find database records that have been stuck in states such as: - `PENDING_UPLOAD` for too long. - `UPLOADED` without progressing to processing. - `DELETE_PENDING` without completing deletion. - `PROCESSING` beyond the expected processing time. For each record, inspect the corresponding object and decide what should happen. For example, if a `PENDING_UPLOAD` record is several hours old and the object exists, we can verify it and resume processing. If the object doesn't exist and the upload has expired, we can mark the record as `FAILED` or clean it up according to our policy. **2\. Storage-to-database reconciliation** We should also periodically identify objects that exist in storage but have no corresponding database record. This is the other direction of the consistency problem. For a small bucket, we can enumerate objects and compare their keys against database records. For large buckets, avoid running an expensive full scan on every reconciliation cycle. Use object inventory reports, scoped prefixes, age filters or storage events to make the process more efficient. Don't immediately delete every object that doesn't have a matching database record. A newly uploaded object might be between the storage upload and database completion steps. Instead, use an age threshold, quarantine suspicious objects if appropriate, and only delete them after confirming that they're genuinely orphaned. **One more thing:** Configure an object storage life-cycle rule to abort incomplete multipart uploads. An upload that was initiated but never completed can leave individual parts consuming storage even though no final object was created. This is another form of storage cleanup that is easy to forget. ### A few production considerations Before we finish, here are some practices I'd keep in mind when building this system. **1\. Never trust the uploaded file blindly.** The client can lie about its filename, extension and MIME type. Validate the actual content, enforce file size limits and scan files for malware where your application requires it. **2\. Keep object storage private by default.** Don't expose permanent cloud credentials in the browser. Generate short-lived, narrowly scoped upload and download URLs only after checking the user's permissions. Also configure CORS correctly for browser uploads. CORS controls which browser origins can make cross-origin requests; it does not replace storage authorization. **3\. Make every background operation retryable.** Network failures and worker crashes are inevitable. Use idempotency keys, conditional state transitions and unique event IDs so retrying an operation doesn't create duplicate assets or corrupt existing records. **4\. Don't buffer huge files unnecessarily.** Stream files through your application when you need to proxy them, and use direct uploads and downloads when the backend doesn't need to handle the bytes. **5\. Monitor the lifecycle, not just the API response.** Track how many files are stuck in each state, how many uploads fail verification, how many orphaned objects are found and how long background processing takes. These metrics help you catch storage inconsistencies before they turn into a large cleanup exercise. At this point, we've covered the entire file lifecycle, including the part that often gets ignored: keeping the database and storage provider in sync. We know where files live, how their metadata is tracked, how uploads and downloads work, and how to recover from failures without leaving a pile of orphaned assets behind. Now there's one final architectural question. **Should we actually own and operate this storage infrastructure ourselves, or should we let someone else do it?** ## 5. Managed vs self-hosted: What should you choose? You have two broad options when choosing object storage: - **Managed storage:** Services like AWS S3 and Cloudflare R2 handle durability, availability, scaling and infrastructure maintenance. You focus on how your application uses storage rather than managing storage itself. - **Self-hosted storage:** Tools like MinIO give you an S3-compatible API while letting you manage the infrastructure. This offers more control, but also makes you responsible for availability, backups, replication, upgrades and monitoring. For most SaaS applications, I'd start with managed object storage. The operational overhead of running your own storage infrastructure rarely makes sense unless you have specific compliance, cost or infrastructure requirements. ### TL;DR — What should you actually do? - Use **HTTP/HTTPS** for browser-based uploads and downloads. Use SFTP when integrating with systems that specifically require it. - Store **metadata and application state in your database of choice**, and file bytes in object storage. - Keep object storage private. Use **presigned URLs** for direct uploads and downloads when appropriate. - Use multipart or resumable uploads for large files. - Use a CDN when files are accessed frequently, especially public assets. - Build retry mechanisms, reconciliation jobs and orphan cleanup from the beginning. Your database and object storage won't magically stay in sync. - Prefer managed object storage unless you have a good reason to operate your own. That's the foundation. The exact storage provider can change; the architecture and practices matter much more. **That's it for this one** If you like this article, consider following me on X at [@Aadi__khare](https://x.com/Aadi__khare), I ~~rant~~ write about a lot of fun tech things there. If you're a nerd like me and LOVE the tech ~~drama~~ insights, you'll enjoy my takes. Until Next Time, **Happy ~~Debugging ~~Coding👋 ** *HTML:* https://adityakhare.com/articles/file-upload-is-broken-let-s-fix-it *Markdown:* https://adityakhare.com/articles/file-upload-is-broken-let-s-fix-it.md --- # Minimal DevOps for Developers **URL:** https://adityakhare.com/articles/minimal-devops-for-developers **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2026-07-06T13:28:29.654Z **Updated:** 2026-07-08T11:44:49Z --- **Summary:** The must need CI/CD practices that every developer should know regardless of the scale of their app What comes to your mind when you hear the word "DevOps"? It's either a sh\*t show of Kubernetes clusters... or you throw your app onto a managed platform like Vercel, Railway, or Netlify and call it a day. Today, as a ~~broke~~ smart developer, I'll teach you how to do minimal DevOps as a developer without emptying your pockets or ruining your mental peace. And yeah it goes much deeper than just using **Docker.** ## What is DevOps and why should you care? Remember the last time you pushed a feature, only for something completely unrelated to break? Or when your app worked perfectly on your machine but refused to run anywhere else? As your projects grow, writing code slowly becomes the easiest part. Building it, testing it, deploying it, managing servers, handling secrets, rolling back bad releases, and making sure everything keeps running become problems of their own. That's exactly the problem DevOps tries to solve. AWS defines DevOps as: > DevOps is the combination of cultural philosophies, practices, and tools that increases an organization's ability to deliver applications and services at high velocity. That's the textbook definition. In simple words, DevOps is just a collection of practices that help teams ship software faster, more reliably, and with fewer "it worked on my machine" moments. And congratulations, you now have the answer to that interview question. DevOps becomes even more important in smaller teams, where the line between a developer and a DevOps engineer is often blurry. More often than not, the same person is responsible for everything from writing code to deploying it and making sure it stays online. That doesn't mean you need to become a DevOps engineer. But every developer should be comfortable with at least these core practices: - Version Control Everything - Automated Testing - Continuous Integration (CI) - Continuous Delivery/Deployment (CD) - Containerization - Monitoring and Observability - Security by Design - Secrets Management - Automated Rollback and Recovery The tools will change depending on your stack, your team, or your company. The ideas stay exactly the same. Let's go through the ones every developer should know, starting with CI/CD. ## CI/CD Imagine you're working on a project with four other developers. Everyone writes code differently. Everyone has a different setup. One person forgets to run the tests, another skips formatting, someone else deploys from their local machine, and before you know it, your production server has become the testing environment. That's the mess CI/CD was created to fix. A CI/CD pipeline automates everything that happens after you push your code, making software releases faster, safer, and far less stressful. **Continuous Integration (CI)** is all about making sure every change you push plays nicely with the rest of the code base. Instead of everyone manually figuring out how to build, test, and validate the project, every developer works independently on their own branch. When they're ready, they open a Pull Request and an automated pipeline takes over. It can install dependencies, build the project, run linting and formatting checks, execute unit and end-to-end tests, and verify that nothing is broken before the code is merged. This lets developers work in parallel without constantly worrying about breaking someone else's work. Once your code has successfully passed all the checks, it's ready to be deployed. The **Continuous Delivery / Continuous Deployment (CD)** stage ensures that you have everything you need to get your app running. That might include building Docker images, provisioning infrastructure, deploying to staging or production, running database migrations, or updating cloud resources. Instead of someone manually logging into a server and hoping they didn't miss a step, the same deployment process runs every single time. Fewer manual steps means fewer mistakes. Now that we've covered the textbook idea behind CI/CD, let's look at how you can apply these practices in your own projects. ## Git Commandments for CI/CD Before you automate deployments, you need to automate discipline. A CI/CD pipeline is only as good as the code that goes into it. Here are my personal non-negotiables that will save you (and your teammates) from countless headaches. - **Make small commits.** They're easier to review, easier to test, and much easier to roll back if something goes wrong. - **One commit, one logical change.** Don't mix a bug fix, a refactor, and a new feature into the same commit. - **Write descriptive commit messages.** Follow a consistent format like [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). Tools like [Better Commit](https://github.com/Everduin94/better-commits) can generate properly formatted commit messages for you. - **Agree on a workflow before writing code.** Whether it's branching strategy, naming conventions, or code reviews, everyone should follow the same process before merging into a shared repository. - **Protect your important branches.** Enable branch protection rules so nobody can accidentally push directly to `main` or delete a production branch because "they thought they were on another branch." - **Prefer a Monorepo when multiple projects evolve together.** If your frontend, backend, shared packages, and infrastructure are tightly connected, tools like [Turborepo](https://turborepo.dev/) or [Nx](https://nx.dev/) can make development much simpler than juggling multiple repositories. - **Always Initialize a workspace with a `.gitignore` :** Accidentally pushing `node_modules`, `.env`, build artifacts, or IDE files is a mistake you don't wanna make. Trust me, you don't want your next GitHub issue to be someone politely informing you that your OpenAI API key is public. ## Multi-Environment Deployments (Dev, Stage & Prod) Let's talk about environments. When you're building your first side project, you usually have just one version of your app (the _live_ one). Every new feature, bug fix, or experiment goes straight there. That works... until it doesn't. As your application grows, a single production environment becomes risky. One bad deployment can break payments, crash your API, or ruin a customer demo five minutes before it starts. This is why almost every serious software team uses multiple environments. A common setup looks like this: - **Development** – where new features are built and tested every day. - **Staging** – an environment that closely mirrors production, where your team can verify everything before releasing it. - **Production** – the version your actual users interact with. Now imagine you've just merged a Pull Request into your `staging` branch. Instead of someone manually copying files to a server, a deployment pipeline automatically builds your application, packages everything it needs to run, deploys it to the staging environment, and gives your team a URL to test. If everything looks good, the exact same process can deploy that same build to production. Platforms like [Vercel](https://vercel.com), [Railway](https://railway.com), and [Netlify](https://netlify.com) do this for you out of the box by automatically creating preview deployments for every Pull Request. If you're into sefl-hosting, tools like Caddy or Nginx can route traffic to different deployments using subdomains or reverse proxies. If you want the best of both worlds, tools like [Dokploy](https://dokploy.com) and [Coolify](https://coolify.io) are also viable options. Here's how you can configure preview deployments in Dokploy. [https://docs.dokploy.com/docs/core/applications/preview-deployments](https://docs.dokploy.com/docs/core/applications/preview-deployments) The tools may differ, but the core idea is this: Every change gets tested in an isolated environment before it reaches your users. ## Containerization should be the norm Containerization is the answer to the age-old question: > "But... it works on my machine." The goal is simple: If two people have the same code and the same configuration, they should get the exact same application running every single time. That's called consistency, and it's one of the biggest reasons containers became the standard. I can't count how many times a colleague pulled my branch (or I pulled theirs), only for us to spend the next two hours debugging why it worked on one machine but not the other. Wrong Node version. Different Python runtime. An outdated Postgres image. A package behaving differently because someone's environment was slightly different. That was my life before Docker. Now every project starts with a `Dockerfile` and a `compose.yml`. A teammate clones the repository, runs a single command, and within a few minutes they're running the same application, with the same runtime, the same dependencies, the same database version, and the same supporting services as everyone else on the team. I can't blame their setup for my bugs anymore. :( Docker made this possible. The best part is that the same containers you run on your laptop can also run in the cloud. Whether you're deploying to AWS, Azure, Google Cloud, or your own VPS, almost every platform today knows how to run containers. Before we go any further, let's clear up a few terms that people often mix together. - A **container** is a running, isolated instance of your application. - An **image** is the blueprint used to create that container. - A **Dockerfile** is the recipe that tells Docker how to build the image. - A **compose.yml** file describes how multiple containers (your app, api server, database and other services) should run together. - **Docker** is the most popular container engine, but it isn't the only one. Alternatives like [Podman](https://podman.io/) exist too. Hell, even Apple has an [open source container engine](https://opensource.apple.com/projects/container/). Hard to believe right. - A **container registry** is simply a place to store and share container images. [Docker Hub](https://hub.docker.com/), GitHub Container Registry, and AWS ECR are some of the most common ones. Once you understand these building blocks, deploying your application becomes much simpler. Instead of saying "run these 17 setup commands before starting the project," you just ship the container. From there, whether you're deploying a single container to a VPS or orchestrating thousands of them with [Kubernetes](https://kubernetes.io/) on services like [Amazon EKS](https://aws.amazon.com/eks/), you're still working with the exact same idea: package your application once, then run that same package everywhere. ## Keep your secrets safe In our [Git Commandments](https://adityakhare.com/articles/minimal-devops-for-developers/#git-commandments-for-cicd) section, we talked about never committing secrets to GitHub, whether they're hard-coded into your source code or sitting inside a `.env` file. Always remember: once something reaches the internet, you should assume it's there forever. Keeping secrets out of Git is only half the battle, though. The other half is managing them. Early on, our workflow looked something like this: - Zip the `.env` file. - Email it. - Send it over Microsoft Teams. - Forward it on WhatsApp because someone couldn't find the email. - Copy the same values into the staging server. - Copy them again into production. - Repeat the whole process the next time an API key changed. We did this multiple times every month. We were an early-stage startup, feature requests changed every other week, and our free startup credits kept pushing us from one cloud provider or service to another. Every switch meant new credentials and another tedious round of updating `.env` files everywhere. And yes, sometimes we'd hard-code an API key just to quickly prototype a feature or demo something to stakeholders. It was a complete mess. One forgotten environment variable or one wrong API key in production was enough to bring the application down. That's why secrets managers exist. Instead of manually sharing and copying sensitive values everywhere, tools like [Doppler](https://www.doppler.com/), [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) and [HashiCorp Vault](https://www.hashicorp.com/en/products/vault) securely store your secrets and inject them into your application only when it's running. Every new developer joining the team gets the latest updated secrets. Nothing in production breaks. Your Git repository never sees anything it doesn't need to. **Everything stays in sync automatically.** It's one of those things that feels unnecessary when you're working alone, but once you've worked on a real team, you'll never want to go back. ## Linting and Formatting I've tweeted this a while ago, and it still holds true to this day. ![](https://cdn.sanity.io/images/r7i2kebp/production/6fb52f8bb153d6842217cb7b92cce59f9b439d82-2268x712.jpg) Most developers think linting and formatting is just an opinionated '_clean code_' practice like **spaces vs tabs **_(spaces obviously)._ They're not. They're about removing pointless discussions from code reviews. A few years ago, I reviewed an intern's Pull Request that was well over **1,200 lines** long. Halfway through the review I realized almost every changed line existed because their editor wasn't adding semicolons while the rest of the project expected them. Git saw every one of those formatting changes as an actual code change. The scary part? That PR almost made it to production. Not because the feature was bad, but because buried inside hundreds of unnecessary formatting changes was the actual business logic I was supposed to review. **Never again.** Today, every project I work on has formatting and linting configured from day one. Tools like [Prettier](https://prettier.io/) and [Biome](https://biomejs.dev) automatically format your code so everyone writes in the same style. Linters like [ESLint](https://eslint.org/) and [Oxlint](https://oxc.rs/docs/guide/usage/linter) catch common mistakes, bad practices, unused variables, and potential bugs before another human even looks at your Pull Request. Use these with the [Ultracite](https://www.ultracite.ai/) preset and you're golden. The goal isn't prettier code. The goal is making sure every Pull Request (whether it's coming from a fresher or an experienced dev) only contains the changes that actually matter, making reviews faster, bugs easier to spot, and your teammates a little less grumpy. ## Git hooks Even with good formatting rules, there's just one tiny 🤏 problem. They only work if people remember to run them, which most devs usually don't 🙂. _Developers are busy_. Sometimes you're rushing to fix a production bug. Sometimes you're committing code at 2 AM after spending four hours chasing a race condition. Sometimes talking to a REAL human on a virtual call is unavoidable 😰 The last thing on your mind is running five different commands before every commit. That's where Git Hooks come in. Git Hooks let you automatically run scripts whenever certain Git events happen. The most popular one is the **pre-commit** hook. Before Git creates the commit, you can automatically: - Format your code. - Run your linter. - Execute type checks. - Run a small test suite. - Prevent secrets from being committed. - Reject commits that don't follow your team's conventions. The best part is that developers don't have to remember any of it. It just happens. A popular tool for managing Git Hooks is [Husky](https://typicode.github.io/husky/). Pair it with tools like `lint-staged`, and instead of linting your entire project, you only format and lint the files you're actually committing. Your commits stay fast, and your team gets consistently clean code. Git Hooks aren't limited to your own machine either. Large organizations use similar automation across their development tools. Atlassian, for example, tightly integrates products like [Jira](https://www.atlassian.com/software/jira) and [Bitbucket](https://bitbucket.org). You can automatically transition a Jira ticket when a Pull Request is merged, enforce approval rules before merging, or trigger downstream workflows without anyone having to remember another checklist. The fewer things humans have to remember, the fewer mistakes humans make. ## GitHub Actions Remember in the [Containerisation](https://adityakhare.com/articles/minimal-devops-for-developers/#containerization-should-be-the-norm) section how a `Dockerfile` is just a blueprint that Docker follows to build and run a container? GitHub Actions work in almost the same way. A workflow file (usually inside `.github/workflows/`) is simply a blueprint containing a list of commands you want GitHub to execute. When a Git event happens (like pushing code, opening a Pull Request, creating a release, or merging into `main)`, GitHub automatically spins up a temporary machine in the cloud, follows the instructions in your workflow file, runs every command one by one, and then throws that machine away once it's done. The only difference is that instead of running those commands on **your laptop**, they're running on **GitHub's cloud infrastructure **_(but you can also self-host them)._ That's all a GitHub Action really is. Github Actions is basically the implementation of CI/CD. All the previous steps can be run through the commands mentioned in the workflow file of a Github Action. These can be: - Installing dependencies. - Checking formatting and linting. - Running unit and end-to-end tests. - Executing type checks. - Building Docker images. - Provisioning cloud infrastructure. - Deploying preview environments. - Uploading build artifacts. - Talking to third-party API services. - Starting, stopping, or cleaning up running resources after the workflow finishes. In fact, almost every managed platform we talked about earlier, whether it's Vercel, Netlify, or larger cloud providers like AWS utilizes these workflows in one way or another. The good news is that you rarely have to build everything from scratch. The GitHub community has already created thousands of reusable Actions for the most common problems developers face. Need to set up Node.js? Deploy to AWS? Build a Docker image? Cache dependencies? Send a Slack notification? There's a good chance someone has already built it. Most of them are freely available on [the GitHub Marketplace](https://github.com/marketplace?type=actions), so instead of reinventing the wheel, you simply plug them into your workflow and let GitHub handle the heavy lifting. But I'll highly encourage you to build one anyway to understand how it works. Github has awesome [documentation](https://docs.github.com/en/actions/get-started/quickstart) on it. **That's it for this one** If you like this article, consider following me on X at [@Aadi__khare](https://x.com/Aadi__khare), I ~~rant~~ write about a lot of fun tech things there. If you're a nerd like me and LOVE the tech ~~drama~~ insights, you'll enjoy my takes. Until Next Time, **Happy ~~Debugging ~~Coding👋 ** *HTML:* https://adityakhare.com/articles/minimal-devops-for-developers *Markdown:* https://adityakhare.com/articles/minimal-devops-for-developers.md --- # Practical Git Guidelines for Professional devs **URL:** https://adityakhare.com/articles/practical-git-guidelines-for-professional-devs **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2025-08-10T06:15:00.000Z **Updated:** 2026-08-23T19:01:58Z --- **Summary:** A more advanced and applicable git guideline for devs who want to learn how tech organisations collaborate with git in the real world. **This is not another git tutorial for beginners. There are a lot of those on the internet.** _I've learned a lot from them myself in the beginning of my career, and all of them are very good at building the foundation and understanding the basic concepts of version control._ _If you don't know what words like 'git' and 'GitHub' mean, you should go find another beginner-friendly tutorial. _ Some of them will be mentioned at the end of this blog. I've noticed that most of the Git tutorials on YouTube doesn't give real world examples of working in production codebases. In this blog, we are going to focus on the necessary parts of the git which you are going to use daily in your job. I'm also NOT going to cover every feature because let's face it, you are not going to use most of them anyway. So, let's get started. ## Quick Refresher OK, so if you've bragged among your friends about the first "Hello World" you wrote, chances are you know about git and its basic commands, namely `git clone`, `git add`,` git commit` and `git push`. But to get a clearer understanding of it, we've visualized it as layers of a pancake in our Top most Picture for this article. Each layer is another part of moving your changes up or not, depending on your command. We can mainly divide the layers into three parts: - **Working directory **_(our local file system where any immediate changes to our files live)_ - **Staging area** _(where files go after we run "git add")_ - **Commit history** _(a permanent snapshot that will eventually be pushed to our remote repository)_ All of the above commands interact with one of these layers in some way. There are also many nuances in these commands, and basically you're never going to just use them in this simple manner in a REAL environment, but we'll get to them over the course of this article. **NOTE: **_we'll be using [this \*repo](https://github.com/aadi-thedevguy/advanced-git-tutorial/) for understanding the concepts in a real world project._ ## Starting the Project The most common and straightforward way to get a local development copy of your remote repo would be just fork the repo and then run `git clone ` on your system, this will basically run a git init and setup you files along with all the previous git history intact. You can also start a new project and push some files to it to follow along _(recommended)_. GitHub already gives you a list of commands to run after you've created a new repo. ![](https://cdn.sanity.io/images/r7i2kebp/production/e9ac9d34644ecd34ef211c125f86bb10c6b243a2-2890x1268.png) If you're using any other platforms like [bitbucket](https://bitbucket.org/) or [gitlab](https://about.gitlab.com), the steps are more or less similar if you follow their respective guides. ## Cloning and Branching #### Cloning `git clone ` is the most essential and commonly used command for any developer. It creates a copy of any repository (local or remote) on your system. Developers use it when they want to dig deep and play around with the code of any repo they find interesting. You can also pass different flags while cloning a repo. The most commonly used flags are _--branch, _which only clones a specific branch `git clone --branch=feature-branch` And --depth flag, which only clones up to the history of commits specified by the flag. `git clone --depth=1` In this example, a clone `<repo>` is made, and only the most recent commit is included in the new cloned Repo. This is known as **shallow cloning **and is most useful when working with repos that have a very large commit history. Cloning a beefy repo with 100s of commits can take a while, so using the depth flag can help you speed up this process. cloning also automatically creates a remote connection called "origin" pointing back to the original repository. So basically running a `git remote add origin ` for you so you can keep up with the master branch changes. **NOTE:** You cannot push changes to a cloned repo because, by definition, it is a clone, so you won't have the write access of the original repository. If you want to work on this cloned copy, you have to first 'Fork' the remote repo to your account and then clone it. #### Branching Ok, so you've already got some changes at your **main/master** branch on your GitHub. Generally, you also have it setup with your hosting platform, where it deploys your changes to a live website or server, ideally to a staging environment to review that your changes work before moving it to production. Now you don't want to just mess with the existing working features pushed by other people in your team to just test you new feature. This is where git branching comes in. It is a way for you to test your new changes without messing up the existing ones. For this, you can create a new branch, usually called 'Feature branches'. So let's say you are working on a project repository with 10+ branches and want to make a new feature request to be merged to the main branch so all the other devs can **PRAISE YOUR AWESOMENESS**. Let's start by listing all branches(both remote and local) for your repo. Run the below command: `git branch --all` This will show you all the branches associated with your repo. ![](https://cdn.sanity.io/images/r7i2kebp/production/ade75d861196b41f5e0119ea8fc4c096601fc096-694x334.png) If everything went well, you can see that we get a number of branches printed in your terminal. The asterisk(\*) shows the current branch you are on. In my case, it's the second feature branch; in your case, it will be your main branch. The top three branches are our local branches, and the branches starting from remotes/origin are your remote branches, i.e. the branches which are in your remote repository. You can also view your local and remote branches separately by running `git branch` or `git branch --list` (for local) AND `git branch -r` (for remote) Now you know the branches, next is to create a new 'my-awesome-feature-branch'. For this, run: `git checkout -b my-awesome-feature-branch` This command creates a new branch and checks you out on it. If you already have an existing my-awesome-feature-branch, you can use `git switch my-awesome-feature-branch` #### Can you switch to a remote branch locally? Well, Yes, But How? `git fetch --all `comes to the rescue. (the -- all flag is optional) It is basically a 'safe' version of `git pull` where, apart from its counterpart, it will fetch all the latest remote branches of your repo **without** updating your local changes that you've made in your working files. You can then checkout to the specific fetched remote branch using `git checkout ` In our example, it could be `origin/feature-branch` or `origin/2nd-feature-branch` Ok, so now you can create a new branch or checkout to an existing branch, now it's time to make changes and push some stuff. ## Contributing in a collaborative environment #### Stashing your changes Let's say you're working in a codebase and you and one other teammate are working on a huge feature on your independent branches. The feature needs the code from 10 files; you're handling 4 files, and your teammate is making changes to the other 6, and your code depends on these. Now your teammate has completed their implementation, pushed the changes to their branch, opened up a new PR, and the Team Lead approved their changes and merged them into the main branch. Meanwhile, you are unaware of the new updated main branch and are still expecting code from outdated files. Git stash helps you here by temporarily taking your uncommitted changes (both staged and unstaged), saving them away for later use, and then reverts them from your working copy. In our case, whenever you find out about the updated main branch from your teammate, you'll run `git stash` to hide (stash) your changes, then `git pull origin main` to fetch the latest changes and then `git stash pop` OR `git stash apply` to get back to your working changes and then update your codebase according to the newly changed files from your teammate. **pop vs apply, which one to use?** `git stash pop` removes the stashed changes altogether from your local system (stash) after taking you back to your working copy, while `git stash apply` keeping them in the stash even after applying them in your current branch. You'll use 'apply' if you want to apply your stashed changes to multiple branches. In our example, when I run `git stash` in my 2nd-feature-branch, after making some changes, it returns the following text in the terminal > > _Saved working directory and index state WIP on 2nd-feature-branch: 2eac1eb Update README.md_ By default, stashes are identified simply as a "WIP" (work in progress) – on top of the branch and commit that you created the stash from. You also aren't limited to a single stash. You can run `git stash` several times to create multiple stashes, and then use `git stash list` to view them. For us, it'll be something like ```sh stash@{0}: WIP on 2nd-feature-branch: 2eac1eb Update README.md stash@{1}: WIP on 2nd-feature-branch: 2eac1eb Update README.md stash@{2}: WIP on 2nd-feature-branch: 2eac1eb Update README.md ``` `git stash pop` by default gives us the most recently created stash: _stash@{0}_ while `git stash apply stash@{2}` or ` git stash pop stash@{2}` will give us a specific stash. If you decide you no longer need a particular stash, you can delete it with `git stash drop stash@{1}` Or you can delete all of your stashes with `git stash clear` You can also view the diff of a stash just like you do for a commit by running `git stash show`, pass the -p flag to get the full diff like below. ```sh diff --git a/README.md b/README.md index 57f2318..50afe3f 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,6 @@ These changes are made to the remote branch (Realistically by another teammate) + + +2nd time file changed for stash \ No newline at end of file ``` **git stash will not work for:** - new uncommitted files - any files mentioned in .gitignore So if we created an 11th file for our feature, but didn't stage it (i.e. ran `git add`), `git stash` won't stash it. You can get around it by adding the `-u` option (or `--include-untracked`) tells `git stash` to also stash your untracked files. **A small issue with stash** Let's say your teammate needed to change one of the 4 files that you've been working on, and it got merged to main. Now, after you've merged the main branch into yours (obviously after stashing the local changes), when you apply those changes back, because of that one file, you'll run into a **merge conflict.** `git stash branch` solves this problem by creating a new branch to apply your stashed changes to. So now, instead of running our `git stash pop` directly and solving merge conflicts, we have the option to run `git stash branch new-branch-from-stash stash@{1}`, This checks out a new branch based on the commit from which you created your stash, and then pops your stashed changes onto it. The result is: ```sh git stash branch new-branch-from-stash stash@{1} Switched to a new branch 'new-branch-from-stash' On branch new-branch-from-stash Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git restore ..." to discard changes in working directory) modified: README.md no changes added to commit (use "git add" and/or "git commit -a") Dropped stash@{1} (76f56cae01242c6c706f9d5ba61daece37f9c484) ``` ### From Commit to Merge My piece of advice in this is the same as I give to every new junior dev I've worked with over the years, that is, to always run git stash and git pull from the **main** branch before committing your changes and pushing to _your branch (as we've covered above)_ In my experience, it's always easier to fix the merge conflicts locally before raising a PR in your local system editor than resolving them during the merge. ![](https://cdn.sanity.io/images/r7i2kebp/production/9bdfd4aa615a20474c9e9762bc520764d29b486c-248x320.jpg) **2 Rules to abide by on how NOT to mess up your repo:** - _Always have **branch protection rules** enabled._ - Use _git revert instead of git reset (especially for public repos)_ Branch protection rules are the THICK line of defense that stops someone else's mistake from ruining your week's hard work. So no one "_accidentally_" pushes 5-week-old garbage code that needs to be deleted to the **main branch.** Basically, you can set specific conditions for your branches to allow/block specific pull/push and commit options to the collaborators of your repo. They work on both public and private repos. You can enable them on GitHub by going into your repo settings and then clicking on branches in the 'Code and automation' section. Then you can click on 'Add classic branch protection rule' to add your rule. ![](https://cdn.sanity.io/images/r7i2kebp/production/4959a879e71594d6bd5987b39b4a2727407e886b-2916x1038.png) Below is the most basic rule that you **MUST HAVE** on your main branch. You can customize and add more rules according to your organisation's requirements. ![](https://cdn.sanity.io/images/r7i2kebp/production/64c9d14dbcae3c416d53e8db74531356969bbcfb-2916x1602.png) In the first image, you can see that we have an option to create a branch rule set, They are a more in-depth and granular way of managing specific permissions within your organisation's multiple repos and branches. I never really need to use them, but you can read up on them more in the [GitHub docs](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) Now that's out of the way, let's talk about committing changes. Or more specifically, '_undo' _a committed change. #### Revert vs Reset `git reset` and `git revert` are both _undo commands._ `git reset` "reverts" back to the previous state of a project by removing all subsequent commits up to the current branch pointer (HEAD). It can also reset your commit history, working directory or your _staged_ _changes_, depending on the flag you passed to it. Running `git reset` or `git reset --mixed HEAD` is the same. **HEAD** is the specified commit. Instead of **HEAD**, any commit hash can be used. For our specific project, we created 4 commits on our new branch '_git reset demo'_ When we run our git log, we see the following: ```sh git --no-pager log --oneline f123793 (HEAD -> git-reset-demo) Fourth commit: Version 4 - Performance optimizations 559f225 Third commit: Version 3 - Fixed critical bug b96894a Second commit: Version 2 - Added new feature 45022d6 Initial commit: Version 1 c4b76a8 (origin/main, origin/feature-branch, origin/HEAD, main, feature-branch) Initial commit ``` Now let's run `git reset --soft b96894a` to reset back to our second commit. Now, if we run our `git log` to see our commit history, we'll see that our second commit will now be the latest. ```sh b96894a (HEAD -> git-reset-demo) Second commit: Version 2 - Added new feature 45022d6 Initial commit: Version 1 c4b76a8 (origin/main, origin/feature-branch, origin/HEAD, main, feature-branch) Initial commit ``` Look closely as we're also using the _--soft _flag here. Using it tells git to only change the commit history, and do not affect our current working directory and staged files. Meaning if we run `git status` now, a command used to display the current state of the working directory and the staging area, we'll see something like this in the terminal: ```sh On branch git-reset-demo Changes to be committed: (use "git restore --staged ..." to unstage) modified: demo.txt ``` If you run `git diff --staged` to see that our _demo.txt file _contains the changes made to it in the 2nd commit, but will have all the changes UP TO our 4th commit in staging. ```sh diff --git a/demo.txt b/demo.txt index 1761bcf..5416988 100644 --- a/demo.txt +++ b/demo.txt @@ -1,4 +1,6 @@ -Version 2: Updated content +Version 4: Final improvements This file will demonstrate git reset behavior. -Current state: Second commit +Current state: Fourth commit Added: New feature implementation +Fixed: Critical bug in the feature +Added: Performance optimizations ``` `git diff --staged` shows you what changes have been added to the staging area with `git add` and are therefore prepared to be included in your next commit. It compares the current state of the files in your staging area to the version of those files that exist in your `HEAD` commit (the most recent commit on your current branch), which in our case will be the **_2nd commit_** as we've reset the commit history to commit 2. `git reset` can also be considered as the inverse of `git add` as it can un-stage any local changes done with `git add` and it also takes the same _\_ argument as **git add** All of this is due to our _--soft _flag. It is highly recommended that if you ever need to use the `git reset`, you should always use it with the `--soft flag`. Now, let's create a new file and make some changes to it. If we run `git reset --hard 45022d6` to rollback our changes to our initial commit, we see the same result as before when we run `git log` but very different when we run `git status`, you'll see that our new file is lost and there are no mention of it in our staging area. This is why we avoid a hard reset; it basically gives you a clean slate. **NOTE: Don't use git reset on public repos after pushing the commit** This should be obvious; other devs might be working on the pushed commits. Resetting those commits can mess up collaboration, making it seem like part of the project history vanished when teammates sync up. It creates a split between your local branch and the central repo’s branch, leading to confusing merge issues. If you need to undo a public commit, use `git revert` instead. It’s built for that. Stick to git reset for local experiments gone wrong. The `git revert` is a **forward-moving undo operation** that offers a safe method of undoing changes. Instead of deleting or "going back" commits in the commit history, a revert will create a new commit that reverses the changes specified. It is a safer alternative to `git reset` in regards to you clawing out your hair after losing your work. Let's create a new _git-revert-demo_ branch and commit some changes to our _Readme.md_ file, our logs show us: ```sh git --no-pager log --oneline 3b53759 (HEAD -> git-revert-demo) final commit 2dd4f85 second commit dcb4d9d initial commit c4b76a8 (origin/main, origin/feature-branch, origin/HEAD, main, feature-branch) Initial commit ``` Now, if we run `git revert HEAD`, we'll be prompted to add a commit message for our _new commit_ in our terminal editor, once we finish editing, and then run `git log` again, we'll see that a new commit with the changes to our file has been added to our commit history, as shown below. ```sh git --no-pager log --oneline a673a29 (HEAD -> git-revert-demo) revert "final commit" 3b53759 final commit 2dd4f85 second commit dcb4d9d initial commit c4b76a8 (origin/main, origin/feature-branch, origin/HEAD, main, feature-branch) Initial commit ``` No changes were lost, you've targeted specific commit changes, and it's very clear to understand if any of your team member gets to work on this code in the future. #### Git Merge and Rebase Phew, we're finally here to merge our changes. `git merge ` merges the specified branch onto the current branch you're running the merge from. So let's say if you've run `git checkout main` and then `git merge feature-branch`, you're pulling the changes from your _feature-branch_ onto your _main_ branch This creates a new “merge commit” in the `feature-branch` that ties together the histories of both branches. Merging is nice because it’s a _non-destructive_ operation. The existing branches are not changed in any way. However it can result in unnecessary commits added to the `feature-branch` commit history and it can overwhelm and confuse other developers working on the project. As an alternative to merge, you can run `git rebase feature-branch` This moves the entire `feature-branch` to begin on the tip of the `main` branch, effectively incorporating all of the new commits in `main`. But, instead of using a merge commit, rebasing _re-writes_ the project history by creating brand new commits for each commit in the original branch. The major benefit of rebasing is that you get a much cleaner project history. First, it eliminates the unnecessary merge commits required by `git merge`. Second, rebasing also results in a perfectly linear project history. > Similarly to `git reset`, the golden rule of `git rebase` is to never use it on _public_ branches. Let's take our above example, what happens when we rebase our `feature-branch` into `main`. The rebase moves all of the commits in `main` onto the tip of `feature-branch`. The problem is that this only happened in _your_ repository. All of the other developers are still working with the original `main`. Since rebasing results in brand new commits, Git will think that your `main` branch’s history has diverged from everybody else’s. The only way to synchronize the two `main` branches is to merge them back together, resulting in an extra merge commit _and_ two sets of commits that contain the same changes (the original ones, and the ones from your rebased branch). Sounds very confusing right? So, before you run `git rebase`, always ask yourself, “Is anyone else looking at this branch?” If the answer is yes, take your hands off the keyboard and start thinking about a non-destructive way to make your changes (e.g., the `git revert` command). Otherwise, you’re safe to re-write history as much as you like. **NOTE: **Most of the time, you'll not use these commands directly from the terminal but a senior dev or team lead will be reviewing your PR, dropping comments for code improvement and later merging it to the _main_ branch using a GUI provided by platforms like Github, Gitlab, Bitbucket, etc. #### git cherry-pick **"Cherry picking"** is the act of picking a commit from a branch and applying it to another. `git cherry-pick` can be useful in cases where a commit is accidentally made to the wrong branch. You can switch to the correct branch and cherry-pick the commit to where it should belong. The usage of **cherry-pick** is pretty straight forward. Let's take an example from the TS development ecosystem, We have two devs, one front-end and one back-end both working on separate feature branches, and the front-end dev needs to make an API call to a specific back end Route, the development of which isn't completed yet but the _result type _of the response is ready to go in a specific commit. The front-end dev can checkout to his own branch, select the specific commit containing the _result type_ and just run run `git cherry-pick `, this will create a new commit on his branch from where he can continue working on his features. Cherry picking is also helpful when you need to ship a bug fix quickly to the end users. Let's say a developer has started work on a new feature. During that new feature development they identify a pre-existing bug. The developer creates an new commit fixing this bug. This new patch commit can be cherry-picked directly to the `main` branch to fix the bug before it effects more users. Apart from the above and some other specific use cases for `cherry-pick` command, `git merge` or `git rebase` are still preferred for most cases. ## Conclusion Git is a very vast technology, and there's still a lot to cover. From different types of flags used along with the commands to pre-commit hooks for linting/formatting to managing different repos for dev, staging and production to having automated checks before merging specific branches, triggers and bots to sync external APIs and a lot more. But all of these will come under Git rules for CI/CD and will be covered in another article, as this has already been long enough. I've tried to cram in the most useful ones in this article, hoping it would be enough for you to claim the title of "git expert" in your organisation. If you like this article, consider following me on X at [@Aadi__khare](https://x.com/Aadi__khare), I ~~rant~~ write about a lot of fun tech things there. If you're a nerd like me and LOVE the tech ~~drama~~ insights, you'll enjoy my takes. Until Next Time, **Happy ~~Debugging ~~Coding👋 ** #### REFERENCES: - [https://www.atlassian.com/git/tutorials](https://www.atlassian.com/git/tutorials) - [https://www.freecodecamp.org/news/git-cheat-sheet/](https://www.freecodecamp.org/news/git-cheat-sheet/) *HTML:* https://adityakhare.com/articles/practical-git-guidelines-for-professional-devs *Markdown:* https://adityakhare.com/articles/practical-git-guidelines-for-professional-devs.md --- # Payload v3, The Ultimate CMS **URL:** https://adityakhare.com/articles/payload-v3-the-ultimate-cms **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2025-01-13T19:02:18.113Z **Updated:** 2026-11-18T10:09:04Z --- **Summary:** My experience of switching to the latest version of payload with NextJs 15 and React 19 > Hey, Can you make this heading a different shade of black and move this Nav Item to the bottom instead of top. Shouldn't take you more than 15 minutes tops - **Marketing Guy** To solve this never-ending problem, **CMS (Content Management Systems) **were introduced. So a developer can just say "DO IT YOURSELF, Ya Punk" next time he gets a request to change the button colour for the 10th time. ## What the hell is a CMS? The idea was to provide an easy, rich, and effective way for non-developers to modify the content on large content-heavy websites without ever touching code. Basically, the developer can take care of the functionality and features and the "Marketing Experts" can manage and update the content however they want. It all started with [WordPress ](https://wordpress.com)**(the OG of CMS)** which bridges the gap between a developer and a business person. It has a wide plugin system for almost every feature you can imagine in a content-heavy website from mailing lists to e-commerce funnels, you name it. PHP Lambo bros loved it as it got the job done. Then, the wave of _JAM(Javascript API Markup)_ Stack apps came around 2017 - 19ish and made it way easier for a programmer to please the shareholders. A whole ecosystem of tools was built to develop websites that are FAST AF, SEO friendly, and easily maintainable both with code (for programmers) and UI interfaces (marketers). This wave also brought a whole new generation of** "headless"** CMS into the mainstream developer community. You can find a list of them on the [JAM Stack Website](https://jamstack.org/headless-cms/). Now unlike WordPress or its other counterparts, the ideology behind headless CMS is that the developer should BYOUI _(bring your own UI) _and_ _it takes care of the _content_**.** This gave them the ability to develop their UI in whatever framework they wanted and just consume the content stored in their CMS via an API or an SDK. ## Why Payload is different than the others? Now over the years, I've tried many of these headless CMS' like **_Sanity.io, Strapi, Contentful_** and many more and all of them are great and flexible in their own ways. They all allow a lot of content blocks (Text, Date, Media etc.) and are easy to work with both from a developer and a business standpoint. But at the end of the day, I'm a developer and I value DX (unlike those marketing guys). I want something as close to my source code as possible. In a way, [sanity.io](https://sanity.io) solved this as you can define your content collections along with your business code in your project. I like Sanity very much, a lot of my projects are built with it. But Payload gives you even better (and granular) control as you _OWN _the underlying tech and infra to the code as well and it ships with your app. This means that there's no magic going on behind the scenes. Let's understand this with an example, suppose I want a blog website where my CMS handles the content. I'm using NextJS as my preferred choice of the framework but it doesn't matter much as almost every CMS exposes its API over HTTP. If I'm using any other CMS, I have to create the schema there and consume it through my app and it will be hosted either on a managed server provided by the company (in case of sanity or contentful) or I have to self-host it separately on a VPS (in case of Strapi) and I would have no idea what the hell is [GROQ](https://www.sanity.io/docs/groq)? But In payload, Your CMS ships with you, which means you have a single source of truth for your UI, business logic, and Content management all in one place. ## Why Should I Care? In short, it'll save you time, cost you less and it's not just for handling content anymore. If it was any other CMS where you don't know what DB is getting used in the background, how are they handling queries, relations, user access and 10 other things, you would most likely only put non-sensitive content, use it in a static landing page, newsletter, course content and call it a day. But with payload especially with v3 stable and the long list of features it provides, you can build the next Facebook if you want. At this point, It's not just a CMS but a established Typescript-based **Backend as a Service **for NextJS** **around my favourite _databases _with _auth built-in _which can be deployed along with my app. ### Some of its features include: 1. Ability to choose your own DB: Postgres, Mongo and now Sqlite too with its new [drizzle](https://orm.drizzle.team/) adapter. 2. Role-based Access Control for easy user management. 3. Magic link signups with forgot and reset password functionality 4. A wide variety of [Plugins ](https://payloadcms.com/docs/plugins/overview)for everything from SEO to cloud Buckets to Stripe and a _lot more._ 5. Everything is Configurable in the Admin Dashboard because everything is just a react component styled with Sass or TaiwindCSS from fields to views. 6. Internationalisation and Dark mode support out of the box. 7. Supports the latest **Next 15 **along with **React 19** Server components, so you can expect faster live previews thanks to the new _React Compiler_. 8. The payload team also introduced Job queues and cron jobs from v3. I'd highly recommend watching the [official release video](https://www.youtube.com/watch?v=5E9ZDXOk0_8) of v3.0 by the Payload team to understand its capability and limitations. ## My Experience I've been following the payload journey since about a year ago when I saw [this video](https://www.youtube.com/watch?v=3JUsg-WsU9o) on the [JavaScript Mastery ](https://www.youtube.com/@javascriptmastery)Channel. I'm an active member of its Discord server and am constantly engaged in conversations about ongoing issues. But I've never used it much as before v3, it supported **GraphQL **by default and I ~~hate~~ am not a big fan of it. Therefore If I really wanted to learn and play around with it, I'd have to set it up from scratch and not many resources were available for it. Thankfully Josh dropped [this video](https://www.youtube.com/watch?v=06g6YJ6JCJU) so it was ~~not a complete nightmare~~ relatively simple to set it up. The problem was neither NextJS nor Payload was stable at that time so I had to "glue together" a half-baked solution with TRPC and ExpressJS for it to work properly. Well, about 4 months later, all of the above changed and v3 is now out and ready. I've migrated my project from v2 to v3 which resulted in much less code with new and stable features and is a joy to maintain and work with. You can check out the project on [GitHub](https://github.com/aadi-thedevguy/shoppagator). It includes both the version so you can compare the differences and improvements. For my use case, I didn't get to utilise many new features like live previews, search, custom admin components and more. So if you want to see a complete app with all these included. You can clone this [starter website template](https://github.com/payloadcms/payload/tree/main/templates/website) from the Payload repo. Therefore I'd highly recommend trying out payload if you have a NextJS app, are short on time, don't want to build your own admin dashboard, or roll your own auth solution without compromising on security and performance. You can watch **Bytegrad's video** on [how to get started with Payload v3](https://www.youtube.com/watch?v=0Pz9g654OIc). to get started with Payload. Well, this is it for this one. Pheww, this took a while. I'll try to write more articles like this at least once a month. **let's see how disciplined I am this year so no promises🤞** Until Next Time, **Happy ~~Debugging ~~Coding👋 and _Happy New Year_** *HTML:* https://adityakhare.com/articles/payload-v3-the-ultimate-cms *Markdown:* https://adityakhare.com/articles/payload-v3-the-ultimate-cms.md --- # How I write code after 3 years in the Software Industry **URL:** https://adityakhare.com/articles/how-i-write-code-after-my-3-years-in-the-software-industry **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2024-09-30T13:00:00.000Z **Updated:** 2026-11-07T12:55:06Z --- **Summary:** How an Experienced Developer writes code - Senior vs Junior Coding Practices _Ok I've been here for some time and **I have opinions**_ _Or as the cool kids say nowadays_ > Started from the bottom, now we're here _First, let's get one thing clear, this post is not for overwhelming or disheartening beginner software developers. In fact, as a genius Engineer once said:_ > _ you should write bad code to write good code _ \- Some random soy JS dev (probably me) All of us have been there. I have written so much bad code that compared to it, running useEffect recursively doesn't sound that big of a deal😐. This post is for newer devs to start thinking about from a different point of view while developing software, and maybe change their approach and mindset to think about scale, outages, traffic, performance, testing and other common yet important concepts. So let's look at some of the common developer dilemmas and strategies to solve them at a high level and then let's dig into some coding examples to compare the code ## The best stack is the one you're experienced with If you've seen the framework wars on Twitter that have been going off for decades, you know that (insert your favourite stack here) is the GOAT. Especially in the JS ecosystem, every day is a day when a new Blazingly Fast, Game-Changing JS Framework, Auth library, JS Runtime or Build Tool is born. I've also been part of this hype train when I started off. I've tried and played around with almost every new Framework, Library, and even databases and languages for weeks and it is so fun for me from the perspective of learning and understanding different concepts and ways of solving problems. I genuinely enjoyed the time I spent on this. So if you're also passionate about this, sure give it a try. But if your goal is to get a Job, find out what's hot and in demand in your area, learn it, follow its coding practices, use its libraries and tech stacks and GET PAID. ![](https://cdn.sanity.io/images/r7i2kebp/production/9a08725280e581f66dc4796cc450b4908b6c0172-500x281.gif) On the contrary, You must have watched or heard about the discussion going on about the opinions of [Peter Levels on the Lex Fridman Podcast](https://youtu.be/Y-tvQm9HW1M?t=168) My 2 cents on this is in the heading of this section and this😌 > Don't take advice from random strangers on the internet who shove their biased opinions masked as advice and claim that this new cool thing is **THE FUTURE **of Development. Meanwhile, 70% of websites still run on PHP and the PHP devs are like ![](https://cdn.sanity.io/images/r7i2kebp/production/fd249b478a95b474ce0a2fff3a7286703e8b06cc-320x316.jpg) If you are an Indie hacker or just a beginner dev trying to get better and faster at coding. Stop switching technologies and just pick one that you enjoy the most right now You can implement similar design patterns and best practices in any programming language and framework. The tough choice is to weigh the pros and cons that your existing stack is right to solve this specific problem and investing the time and effort to learn this new shiny thing is worth it and eventually gonna pay it off in the long run. ## Use Typescript Of course, If you are a JS dev. If not what the hell are you doing on my Blog? JS was originally made as a dynamic scripting language for the web and I know that with NodeJS we have a great ecosystem for server-side development with JS but the idea of JS running on the server didn't really sit well with me. Static Type Checking is essential in any server-side language for me. With TS, I can write better, safer code and don't have the urge to blow my head off any time I see `cannot read properties of undefined (reading 'yourmom')` and TS prevents this by converting a dynamic language into a Static Type-Safe one. It also gives you nice IntelliSense in your IDE while accessing object properties and enforces strict yet customizable rules like null checking, params and return types while writing code so you can catch bugs right in the editor instead of runtime. Almost every new library, framework and now even runtimes like deno and bun just come with TS support out of the box. Nowadays I write TS even if I'm building a SPA client app with any UI framework. Modern Full-Stack frameworks like NextJS, Remix, Astro etc. along with ORMs like Prisma, Drizzle and Zod for validation make it even more frictionless to write TS on both client and server and ensure full type safety right from the database all the way to your UI giving a seamless DX along the way. Now it's not all [Guns and Roses](https://open.spotify.com/artist/3qm84nBOXUEQ2vnTfUTTFC) or whatever the saying is. If you're using NodeJS, You have to run an additional compile step that converts your TS files back to JS before you can use Node to serve your application and the compile time, well let's say it can be pretty slow at times and add a bit of complexity to your app but modern toolings like esbuild and TS supported runtimes like deno, Cloudflare, bun etc. solves this. Oh and with TS, you can just > _Skip non-essential Shit like Writing Tests_ **_Yup, I said it, come at me Tech Twitter 😎😏_** If you're too deep into JS and not ready to let it go, you can progressively adapt TS just as Microsoft intended for it to be used. You can try it on the server first and then move on to the client with the help of the full-stack framework mentioned above. Anyhow I highly recommend giving it a try before hating on it. Even if this didn't convert you and all of this sounds like extra work, then at least check out [JSDoc ](https://jsdoc.app/)along with ESLint which will get you almost 70% of the way TS could. ## Don't reinvent the wheel You must have heard this before, but building something from scratch is a waste of time and effort, Your job as a Programmer is to solve problems faster and efficiently and it doesn't make sense to code every feature from scratch to achieve a common functionality unless if you're a FAANG Engineer in which case, Why are you doing here? You must have 10 tickets to raise and a dozen emails to send to your seniors before getting the approval to change the CTA button Color from black to White. Expect them, it is always good to rely on tried and tested production-ready solutions instead of re-inventing the wheel. I'd like to quote ~~Myself~~ **that one genius engineer** again. > Perfectionists don't make money, they argue on X about how PHP still sucks and how your app with 0 active users should be able to handle 1 million concurrent request per second. Take [Marc Lou](https://x.com/marc_louvion) for example, an Indie maker who shipped 25+ products in 3 years, made over a million dollars and uses doesn't use TS, doesn't test his code, has no git branching, ships directly to production and hasn't changed his boring Next, Tailwind, MongoDB and Vercel stack in 3 years. Now if you're in a company, Don't be like Marc, test your code and **Don't push to Prod.** The point I'm trying to make is You need to work with tools and languages **you and your team **are familiar with to ship and iterate faster. Even if the tools sound boring and your mind wants to jump to the next new hype on tech Twitter. Remember, > It's doing the boring things over and over that helps you succeed. Either use open-source tools as much as you can if your company allows it or use existing systems, processes and frameworks that your team has developed over the years. ![](https://cdn.sanity.io/images/r7i2kebp/production/cd8c61ca826e2a0d7fe660667bfe46332c8200aa-500x530.jpg) ### Let's compare the differences in the code choices between a Junior and a Senior Dev The below code snippets are written in JS/TS but the concepts are the same and can be converted in any programming language. #### _1. Caching_**:** Server-side caching is crucial for optimizing performance, especially for high-traffic endpoints. Proper caching strategies can significantly reduce server load and improve response times. Junior devs often overlook caching, leading to performance bottlenecks. ```javascript import Redis from 'ioredis'; const redis = new Redis(); async function getUserData(key) { // No caching implemented // directly hitting our primary db const data = await fetchFromDb(key); return data; } async function fetchFromDb(key) { // Simulate database fetch return `Database result for ${key}`; } ``` While Senior devs use some sort of memory store, Redis in our case first check if we have the in-demand data in memory or not, If there's no data only then we hit our primary db. ```typescript import Redis from 'ioredis'; const redis = new Redis(); function cacheData(key : string, ttl: number = 30) { // check if data exists in the cache let data = await redis.get(key); if (data) { return JSON.parse(data); } else { // if no data, hit our primiary db data = await fetchFromDb(key) // and set the new data to our cache with a new time to live await redis.set(key, ttl, JSON.stringify(data)); return data; }; } async fetchFromDb(key: string): Promise { // Simulate database fetch return `Database result for ${key}`; } ``` **Bonus: **You can also use redis to rate limit requests going to your server so that attackers cannot spam your server with consecutive requests. It integrates very well with the `express-ratelimit` and many other nodejs packages. Because frankly I don't get [why someone would still use express](https://blog.thedevguy.in/articles/express-vs-hono) in 2024 when you have so many good options today but to each their own. #### _2. Querying Data:_ Querying data effectively is very important for decreasing API response time specially when handling large datasets. Junior developers often fetch all data at once, causing performance issues. They also don't utilise indexes to speed up their queries. ```javascript // fetching all data at once async function fetchAllData() { // no indexing considered return db.query("SELECT * FROM data WHERE field = 'value'"); } ``` Senior developers implement pagination along with indexes while querying large datasets to fetch a specific range of records instead of all of them and index certain columns for faster retrieval of indexed records. This is helpful in optimizing data fetching and reducing server load. ```typescript // Ensure an index is created on the field db.collection('data').createIndex({ field: 1 }); // paginated data in chunks to reduce server load async function fetchPaginatedData(page: number, pageSize: number): Promise { const offset = (page - 1) * pageSize; return db.query("SELECT * FROM data WHERE field = 'value' LIMIT $1 OFFSET $2", [pageSize, offset]); } ``` #### _3. Data Mutations:_ Handling Data Mutations on the server is a crucial part that you have to think about while writing code that scales. Whenever you update multiple tables in your database, you don't want to be stuck in a state where some records update while others fail. Transactions are a way to perform multiple mutation actions one by one which provides an effective way to instantly roll back the database state in case any of the actions fail. This ensures data integrity during multiple database operations. Junior developers often skip transactions, risking data inconsistency. ```javascript async function updateData(key, value) { await db.execute("UPDATE data SET value = $1 WHERE key = $2", [value, key]); await db.execute("UPDATE logs SET action = 'update' WHERE key = $2", [value, key]); } ``` Senior developers use transactions to handle complex data mutations safely ensuring data consistency and integrity. ```typescript async function updateDataTransaction(key: string, value: string): Promise { const client = await db.connect(); try { await client.query('BEGIN'); await client.query("UPDATE data SET value = $1 WHERE key = $2", [value, key]); await client.query("UPDATE logs SET action = 'update' WHERE key = $2", [value, key]); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); } } ``` #### _4. Server logs and Error Monitoring:_ Effective logging and error monitoring are essential for maintaining application health and diagnosing issues. Junior developers might implement basic logging without structured formats or centralized monitoring. You don't want to be in a situation where a user has to inform you that your app stopped working. This is what logging in a junior dev's codebase looks like. Now if anyone on the team wants to check logs, they have to SSH into the VPS, run pm2 logs or whatever else you are using and see the logs manually and hope to god that they resolve the issue fast before other complaints start flying in. ```javascript const express = require('express'); const app = express(); app.use((req, res, next) => { console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`); next(); }); app.use((err, req, res, next) => { console.error(`${new Date().toISOString()} - Error: ${err.message}`); res.status(500).send('Internal Server Error'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` Senior developers use advanced tools for structured logging, centralized monitoring, and alerting through Slack, discord or email channels. You can use any of the popular logging and monitoring services like Datadog, logstash, posthog, sentry etc. We're using Loki Grafana in the below example. We only need to set a logging middleware in our web app and through the Grafana dashboard, we can customise where we want to receive our alerts. ```typescript import express, { Request, Response, NextFunction } from 'express'; import { createLogger, transports, format } from 'winston'; import LokiTransport from 'winston-loki'; const app = express(); const logger = createLogger({ level: 'info', format: format.combine( format.timestamp(), format.json() ), transports: [ new LokiTransport({ host: 'http://localhost:3100', labels: { job: 'express-app' }, json: true }) ] }); app.use((req: Request, res: Response, next: NextFunction) => { logger.info('Request received', { method: req.method, url: req.url }); next(); }); app.use((err: Error, req: Request, res: Response, next: NextFunction) => { logger.error('Error occurred', { message: err.message, stack: err.stack }); res.status(500).send('Internal Server Error'); }); app.listen(3000, () => { logger.info('Server is running on port 3000'); }); ``` #### _5. Database migrations, Replicas and Backups: _ While Juniors always leave everything up to chance. Senior developers always manage database migrations effectively, have replicas in place for the production db and backup old data at regular intervals to multiple data centres at different locations. To learn more about these database-related topics in detail, check out [my latest post](https://blog.thedevguy.in/articles/lets-talk-about-data-security) on this topic. #### _6. Testing:_ This may be a counter-intuitive take but I don't do unit or integration testing for my products, most of the companies I've worked with either had a dedicated testing team or only did End-to-end tests so I don't have much of an opinion on this. Maybe will write a post on how to do e2e testing in the future. For now, my take is if writing tests doesn't slow you down, only then you should do it. Otherwise, good PR reviews, a good setup of development and staging environments, and Unopiniated coding practices are good enough reasons for you not to write tests. This paired with the above points we discussed in this post will increase your code quality, If you still need tests, You have a **_skill issue_** buddy. Well, Enough Opinion for one post. Until Next Time, **Happy ~~Debugging~~ Coding👋** *HTML:* https://adityakhare.com/articles/how-i-write-code-after-my-3-years-in-the-software-industry *Markdown:* https://adityakhare.com/articles/how-i-write-code-after-my-3-years-in-the-software-industry.md --- # Lets talk about Data Security **URL:** https://adityakhare.com/articles/lets-talk-about-data-security **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2024-08-30T05:50:08.549Z **Updated:** 2026-06-17T06:31:38Z --- **Summary:** Tips and strategies to implement security for bulletproofing your User Data from possible cyber attacks _Securing your User Data is one of the most crucial yet underrated parts of any software if your goal is to avoid something like the [Resend incident](https://resend.com/blog/incident-report-for-january-10-2024), or a **lawsuit **in other cases._ Ensuring the security of your user data is very important if your product has any chance of working out in the long term. So, let's talk about some of the best practices you can use to avoid losing > Your Precious User Data ![](https://cdn.sanity.io/images/r7i2kebp/production/9022a3f47f19c9cbddf862660d80d29a02e81f1c-1920x1100.jpg) **NOTE: **All of these practices apply to all kinds of SQL/NoSQL databases. First Let's look at some ways to secure our DB on the basis of where it is hosted. ## IP Whitelisting IP Whitelisting basically allows us to only connect to a database cluster from a trusted IP address. You can create a list of trusted IP addresses, referred to as an IP access list, that can be used to connect to your cluster and access your data. Use IP whitelisting if you’re connecting to a cloud database like MongoDB or Neon Postgres so that only requests coming from your own servers can hit the database. You can set up your IP access list in MongoDB by following the [official docs](https://www.mongodb.com/docs/atlas/security/ip-access-list/). ## Docker Networking Container networking refers to the ability for containers to connect to and communicate with each other, or to non-Docker workloads. If you want to make a container accessible to other containers, it isn't necessary to publish the container's ports. You can enable inter-container communication by connecting the containers to the same user-defined `bridge network`, so they can communicate with each other using container IP addresses or container names. You can read more about how to configure a user-defined network to only allow incoming network requests from specific IP addresses of your server containers at the [official docker hub docs](https://docs.docker.com/engine/network/tutorials/standalone/#use-user-defined-bridge-networks). ### Virtual Private Cloud (VPC) VPC as the name suggests is basically your own private cloud outside of the public internet which no one else has access to. You can use VPC to host your server and db so that outside public internet cannot connect directly to it. Almost all big cloud service providers like AWS, GCP and Azure offer VPC or VPS (Virtual Private Servers) which may cost more than normal public instances but ensure top-tier security of your user data. These are configurable with a set of policies and rules which I'm not an expert to explain in detail as it is a bit complex DevOps topic, but [@webdevcody](https://youtube.com/@webdevcody?si=eb1yjpZbIciKD2T8) has a great video about [securing your databases with a VPC](https://youtu.be/rt4W45aj2Lo?si=2Gq0l9QPFHT0REGZ) that you should check it out. Now, let's look at some **Simple** security practices to ensure data security in your apps: ### 1. Don't use Firebase on the client Now, I'm not against Firebase I love it and use it a lot for quickly prototyping my MVPs or for delivering a freelance project as fast as possible for a client where deadlines are rather short. What I'm against is using Firebase, Appwrite or any other BaaS which lets your client directly connect to your DB, if you want to do so, set a server specifically for connecting to your DB and exposing REST API endpoints to achieve any DB transaction. Don't forget to set **STRONG **[security rules](https://firebase.google.com/docs/rules/) so that only authenticated users with specific permissions can access data. ### 2. Never trust anyone with your user data If you're not living under a rock, you must know that there's this ongoing debate on X after this [Lex Fridman Podcast ](https://youtu.be/Y-tvQm9HW1M?t=168)YouTube clip by Levelsio went viral in which he talks about how paying a VC-backed company a lot of money to do the work that can be easily done by yourself with a little bit of time and effort. My thoughts are that if you are not a startup or indie hacker that needs to ship as fast as possible and are currently at No/Very Few Users, Sure use whatever services make you more efficient. > **_But OWN your User Data_** Why do you think all the big companies roll their own auth solutions? Because they cannot afford to compromise the Data Privacy of their users and You shouldn't also > **_You CAN roll your own Auth_** You should always use tried and tested production-ready auth strategies and open source libraries like authjs, super tokens, passport js, lucia auth, auth0 and many more so you don't have to build everything from scratch but you should never compromise on your user data with a third-party vendor. Most Cloud Solutions like the _Triangle Company_ can get very expensive very fast as your user base grows. Another reason why I'm against this is **data egress fees** which are the fees levied on you when you decide to step off of their platform, generally, these fees are so high that you would rather pay them than migrate your data which is so hard in itself without breaking stuff. Your data should be kept in **your own database** in multiple replicas and backups. Remember if you don't know where or how your user data is kept,**_ it is not safe._** ### 3. Avoid Dropping User Tables🤦‍♂️ You know what I'm talking about. You've just joined a new company and are working late on a Friday night to impress your new team but in your heart, you want to go to the comic book store to read the newest issue of _Dark Knight: Chaos at Arkham_ and during data migration, you forget to take a backup and accidentally drops the user table and poof just became another victim of layoffs. But in all seriousness, **DON'T PUSH TO PROD ON FRIDAY** - **Take regular database backups: ** set up a weekly/monthly cron to back up your data either to a local server or a server at a different location to avoid data centre outages. Many cloud providers today do this for you with the click of a button. You can read about Mongo Atlas' backup policies [here](https://www.mongodb.com/docs/atlas/backup/cloud-backup/overview/). Neon Postgres doesn't provide backups yet but you can still use the good old `pg_dump,` Read [these docs](https://neon.tech/docs/manage/backups) on how to do so. - **Sanitize user queries before running a database transaction: ** Don't just put whatever you get from the client directly into the database. Especially SQL (I've been a victim of this). Validate client Data and sanitise the inputs so that attackers cannot just pass `DROP TABLE users;` and nuke your countless hours of reading _Design Patterns._ These were some of my strategies to ensure data privacy and safety of user data for the apps I've built that I've learned after fucking up over and over again. Hope you'll not make the same mistakes as me after reading this. What else did I miss? Let me know on [X.](https://x.com/aadi__khare) Until Next Time, **Happy ~~Debugging ~~Coding👋** *HTML:* https://adityakhare.com/articles/lets-talk-about-data-security *Markdown:* https://adityakhare.com/articles/lets-talk-about-data-security.md --- # Dot Notation vs Destructuring **URL:** https://adityakhare.com/articles/dot-notation-vs-destructuring **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2024-08-23T06:00:00.000Z **Updated:** 2024-08-26T13:33:46Z --- **Summary:** A battle for superior code readability or just an opinion going on in the software industry _I believe it’s been so long since my last blog post, I forgot I even had a blog 😅_ _Well, A LOT has happened since then, I switched two jobs, learned a TON of new stuff, faced a burnout and SO much more but I believe that deserves a blog of its own._ _Even though I wasn’t writing on my blog, I was still tweeting whenever something came to my mind, (by the way if you are not following me there,_ _[**you should**](https://x.com/Aadi__khare), I tweet cool stuff sometimes 🤷‍♂️)_ _So After all this time, I’m writing this post to answer the question that has been bugging me for a while that I saw on a tweet a while ago. It’s more of an opinionated rant but I believe someone out there might have similar thoughts and maybe find it useful._ _I’ll try to post more of these rants & opinions consistently in the future. but hey, No promises 🤞_ ```javascript // importing a module import {formatDate} from "./utils" formatDate(new Date()) // utils.js export const formatDate = () => { } ``` ```javascript // importing the whole object import utils from "./utils" utils.formatDate(new Date()) // utils.js function formtDate() { } export { formatDate} ``` _You must have seen the above code snippets once in your life and must have wondered Why One over the Other_ Well today, let’s answer this once and for all ## Brief History of ESM Modules As per the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) , ESM modules were introduced in ES2015 and were a part of the ES6 specification. The ESM modules were introduced as a standardized way to import and export modules in JavaScript. They were designed to be a standardized way to import and export modules in JavaScript. Fast forward to now, if you’ve ever worked with any Modern JS Frameworks like React, Angular, Vue, Svelte, or Solid, all of these rely on ESM modules. ```jsx const LazyLoadedModule = await import("./HighComputationalComponent") import { Suspense } from "react" function App() { return (
Loading...
}> ) } ``` The above snippet is in react based but you can achieve the same in any framework. What we are doing here is we are lazy loading the module and only loading it when it is needed. This is very effective performance-wise but I’m going off-topic here and this doesn’t concern our syntax-related debate. Sorry for that 😅, Moving on. ## 1. Tree shaking and small bundle size🌲 Show the above code to any engineer who worked with a bundler and he will immediately point out that the module pattern is far better because of “tree shaking”, which results in a much smaller bundle size which is very important especially if you’re working in a frontend environment as you want to ship as little JS to the client as possible so the browser can quickly load and execute which increases performance. This is very effective as you’re only bundling and shipping the code that is being used in your application instead of importing the entire module and all of its methods when you are only using some of them. Tree shaking is particularly helpful in scenarios where you’re using a large number of third-party packages. ## 2. Readability and developer experience So the destructuring syntax while importing a module takes the win for bundle size, but when it comes to readability, things become a bit more complicated. You might have heard this quote before, but I’ll put it here for the sake of completeness. > Beauty is in the eye of the beholder. Well, this shit doesn’t apply to code Because everyone has their own opinion on what ensures good code readability and maintainability. In my last job, our team loved encapsulating functions inside a **HUGE** object and then exporting it. This is a very common pattern in JavaScript and solves some very common problems. My favourite is, you can use any name for a function and because it is localised to the object that you are exporting, you don’t have to worry about naming collisions. ```javascript // customers.js export const customerService = { getCustomers() { // some magic here } } ``` ```javascript // subscribers.js export const subscriberService = { getCustomers() { // some magic here } } ``` ```javascript import {customerService} from "./customers" import {subscriberService} from "./subscribers" const customers = customerService.getCustomers() const subscribers = subscriberService.getCustomers() console.log(customers) console.log(subscribers) ``` As you can see, the same function names are in the same file, with no conflicts. So Cool. If you want to achieve the same by using modules and you would have to do something like this. ```javascript import {getCustomers} from "./customers" import {getCustomers as getSubscribers} from "./subscribers" const customers = getCustomers() const subscribers = getSubscribers() console.log(customers) console.log(subscribers) ``` Also if you are a VS Code user, both approaches will give you the same autocomplete suggestions so **+1** to both of them. But personally, because I hate naming things, I prefer the second approach so I don’t have 1 extra name to think of for my exporting object and I can just add a namespace like `getSubscribedCustomers` to my function and be done with it. But for a large item that wants its developers to follow one specific naming convention, the point for better DX and maintainability goes to the dot-notation approach. ## 3. Destructuring Function Parameters and Return Values Until now, we’ve only talked about importing and exporting modules, but what about the functions and basic control flow? Look at the code snippets below and Ask yourself which one you find more readable ```javascript function mapUserNameWithAge({name, age}) { return `${name} : ${age}` } ``` ```javascript function mapUserNameWithAge(user) { return `${user.name} : ${user.age}` } ``` Both functions take an object, one destructures the properties and the other doesn’t. An argument with the first example is that it loses the context of the arguments i.e. we don’t know where it came from and what is the significance of it. But in my opinion, if you provide a clear name that describes the action of the function, it does not matter. Like in the above example, if I named my function something generic like `formatData` Then, maybe the dot syntax makes more sense. Similar case is when you destructure properties or methods that you know you have to use multiple times in your code, but you don’t know what they are called, so you have to use the dot notation to access them. But if I am getting a good intellisense in my IDE, then It won’t make much sense to use the dot notation ```jsx // ❌ Bad const user = getUser() return ( <>

{user.name}

{user.bio}

{user.profile_pic} ) // ✅ Good const {name, bio, website, profile_pic} = getUser() return (<>

{name}

{bio}

{profile_pic} ``` The definition of _good_ and _bad_ in the above code snippets can easily be interchanged depending on the context and preferences of your team. I realised that there are _two kinds of coders_ in the world, > Those who write understandable code for themselves #### **AND** > Those who write code that is understandable by others. You have to decide which one is you Phewwww 😥, This small rant has gone a bit longer than expected. Did I miss any scenario, What is your opinion on this? Please tell me on Twitter. Until Next time, **Happy ~~Debugging ~~ Coding👋** *HTML:* https://adityakhare.com/articles/dot-notation-vs-destructuring *Markdown:* https://adityakhare.com/articles/dot-notation-vs-destructuring.md --- # What is MVC Architecture in NodeJS **URL:** https://adityakhare.com/articles/what-is-mvc-architecture-in-nodejs **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2023-06-23T06:00:00.000Z **Updated:** 2026-11-18T10:29:47Z --- **Summary:** How do I use this architecture to structure my Backend Projects for maximum efficiency while adhering to all the industry practices _It's been a long since I wrote a blog so I thought let's try something not everyone talks about. The Importance of Best Practices and Design Principles for a Web Developer. This will be my first blog regarding backend development. Let's get Started..._ ## What the Heck is MVC? First of All, MVC stands for Model-View-Controller. A certain set of rules/principles for maintaining your Code Structure is quite popular in Backend Development. It suggests separating our file structure into three parts and dividing the logic of our app by its utility. ![](https://cdn.sanity.io/images/r7i2kebp/production/de525f8a087dfcb04e6644af0bd9ecc054a5ea33-279x426.jpg) ### Now let's dig deep into each one of them. ## 1. MODEL The Model contains the Schema of your app which can be defined by any ORM (Object Relational Mapper) or ODM (Object Document Mapper) of your choice. The sole purpose of a Model is to interact (query/store) with the Database from your App. Basically storing your app data in a database with the help of Schema (the structure in which the data should be stored) generation is done by the Model Files. ```javascript // models/goal.js const mongoose = require('mongoose'); // save our data in our database according to our given schema structure const goalschema = mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' }, text1: { type: String, required: [true, 'Please Add a Text Value'] } }, { timestamps: true }); module.exports = mongoose.model('Goal', goalschema); ``` ## 2. View The user doesn't care about what your app does behind the scenes. He only cares about the data it receives when it sends a Request to the server. The View files are primarily your HTML, CSS and JS files but can also contain other static files like Videos, Images or any Other Text or Media files. In Node JS Express Framework, these files go into the Public folder which gets delivered to the Browser by the Server as a response whenever a certain request is made. The general purpose of our Views is to display the data in a user friendly manner to the Client (Web Browser). ![](https://cdn.sanity.io/images/r7i2kebp/production/ca5aedb2be7ef63d1f55e099a2c96c0aa5f5661a-248x191.png) ## 3. Controller This is what Controls the main business logic of our App. While using NodeJS, we refer to these as **Routes** files. It basically works as the thread between our Models and Views. It stores and retrieves data from and to our Models and sends the data to the Views to send it back to the Client. In an Express environment, these files work on the principles of taking a request from our Views and sending data as a response to the user. We can also extract the logic of these files in a separate Controller file which processes all the computation and logic of our app. This is basically a good Coding practice to keep our code concise, clean and Reusable. ```javascript // Logic/function to run when someone hits the below route // Description Get Goals // Route GET /api/goals // Access Private const getGoals = asyncHandler( async (reg,res) => { const goals = await Goal.find({ user : req.user.id }) res.status(200).json(goals) }) ``` In the below snippet, our Route File runs the Controller function called _`Login`_ and Returns data whenever our login API endpoint gets hit. ```javascript const express - nequire("express") const router - express.Router() const {login, dashboard} = require("../controllers/main") const authmiddleware = require("../middleware/auth") // send the below response for our user to view when they hit the below Endpoint router.route("/dashboard").get(authhiddleware, dashboard) router.route("/login").post(login) module.exports = router ``` I hope this blog gave you some basic Ideas of the practical meaning of the MVC architecture and what should be your approach for structuring a new Express App. Until Next Time... **Happy ~~Debugging ~~ Coding👋** *HTML:* https://adityakhare.com/articles/what-is-mvc-architecture-in-nodejs *Markdown:* https://adityakhare.com/articles/what-is-mvc-architecture-in-nodejs.md --- # ExpressJS VS HonoJS **URL:** https://adityakhare.com/articles/express-vs-hono **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2023-02-26T06:00:00.000Z **Updated:** 2026-11-18T10:30:25Z --- **Summary:** A Battle for the minimalist and most Effecient NodeJS Backend Framework _As a MERN Stack developer, I've always appreciated the minimalist approach of the Express framework. It has been my go-to for setting up a web server, even for minor server functionalities. But recently, I found myself at a crossroads. The diverse JavaScript ecosystem_ ## The Express Journey Our ~~messed up~~ **_Diverse_ **Ecosystem of JavaScript offers a plethora of backend frameworks, each with its own strengths and quirks. NestJS, Fastify, Koa, and even NextJS (if you consider it a backend framework) are all compelling options. As a beginner, I naturally gravitated towards ExpressJS — the tried-and-true choice. However, as I matured in my development journey, I began to notice its limitations. Express hadn't fully embraced modern web standards like some of its counterparts. NextJS and Astro, for instance, stood out with their better developer experiences and serverless deployment capabilities. Oh, and Typescript just works out of the box🤩. ## Enter Hono Amidst this dilemma, I stumbled upon a [**_short video_**](https://youtube.com/shorts/NkzzHYp3gag?si=ls7TdFV0qPJQbNmD/) by Ben Holmes. It mentioned Hono - a modern backend framework that promised speed, lightweight design, adherence to web standards, and compatibility with any JavaScript runtime. But what really caught my attention? [**_Hono’s router outpaced_**](https://hono.dev/concepts/benchmarks#routers) all the other frameworks I’d considered. ## Enough Story Time—Let’s Code! Now let’s roll up our sleeves and build something. How about a tasks manager app to track your New Year resolutions. #### The app should include: - Authentication and Authorization - MongoDB for storing our tasks - CRUD functionality for our tasks **_We’ll build with both Express and Hono and evaluate the pros and cons of both on the basis of:_** - Developer Experience - Performance - Bundle Size - Flexibility ## 1. App Structure ![](https://cdn.sanity.io/images/r7i2kebp/production/b6fd6c92bc6747696219c07a1006ca27a2bf402e-655x680.png) The above file structure should be familiar to you if you’ve used Express before. The `index.ts` file is the entry point of our server. We have the same Model View Controller architecture along with an auth middleware for protected routes. We are using Typescript (obviously 🤷‍♂️) so we have defined some files for the reusability of our interfaces and enums. One additional advantage with Hono is that it comes with Typescript by default. In Express you have to configure it yourself. Hono can be configured with multiple deployment/server options, I’m currently using the [**_NodeJS server adapter_**](https://hono.dev/getting-started/nodejs) in this demo but you can use whichever deployment option fits your needs. ## 2. Router One notable difference is that Hono doesn’t allow abstracting away the callback function of a route in a separate controller file. But fear not! As your codebase grows, you can always create utility functions to encapsulate specific business logic. Now, let’s compare how we’d fetch a list of tasks for a user using Express and Hono. The below code is in our `tasks.router.ts` file ```typescript import { Router } from 'express'; import { taskController } from './task.controllers'; import { protect } from '../middleware/auth'; /*Fire the router function*/ export const tasksRouter: Router = Router(); // Create a get route. tasksRouter.get('/tasks', protect, taskController.getAll); ``` The actual business logic will be written in a separate controller file `tasks.controller.ts` ```typescript const getAll = async ( req: MyRequest, res: Response, ): Promise => { if (!req.user) return res.status(404).json({ errors: 'Not Authorized' }) try { const tasks = await Task.find({ user: req.user.id }) return res.status(200).json(tasks) } catch (error) { return res .status(500) .json({ errors: 'Internal Server Error' }); } }; export const taskController = { getAll }; ``` Hono is much more like the API endpoints of NextJS Instead of abstracting the business logic into a new controller file, the Hono docs recommend that we write all the code related to a particular route right there in the `tasks.router.ts` file so that Typescript can properly infer the types. ```typescript const router = new Hono() router.get("/", protect, async (c) => { const user = c.get("user"); if (!user) { return c.json({ error: "Not Authorized" }, 401); } try { const tasks = await Task.find({ user: user.id }); return c.json(tasks, 200); } catch (error) { return c.json({ error: "Internal Server Error" }, 500); } }); ``` In the above code Snippet, the router works similarly to express where you import your **_Router_** in your `index.ts` file `const app = new Hono()` and `app.route("/api/tasks", tasks);`. you also receive a context object in the callback function, which lets you access the request headers, query params, form data, JSON body etc. and also lets you return JSON, Plain Text, HTML and even JSX as a response. It’s pretty neat. ## 3. Lightweight yet Batteries Included If you’ve used Express before, you have to set up middleware for even the basic stuff required for a good server. This can be a good thing for experienced devs as it gives them more control to pick or not to pick a certain package but can be confusing for beginners. You have to install separate packages for setting up _cors_, _form submissions_, _file uploads_, _secure headers_, _JSON web tokens_, _session cookies_ etc. While Hono has everything a good backend framework needs, it has built-in middleware for everything above. **Let’s take a look at the** **`index.ts`** **files in both scenarios** #### Express ```typescript import express, { Express} from 'express'; import cors from 'cors'; import dotenv from 'dotenv'; import helmet from "helmet"; import morgan from "morgan"; import connectToDB from "./utils/db"; import users from "./routes/users"; import tasks from "./routes/tasks"; // Instantiate express app const app: Express = express(); dotenv.config(); // Parse request Body app.use(express.json()); app.use(express.urlencoded({extended : false})) // Use CORS for restricting requests from unsafe origins app.use(cors()); // Use Helmet for adding security headers app.use(helmet()) // use Morgan for logging requests app.use(morgan('tiny')) app.use('/api/auth', users); app.use('/api', tasks); const port = process.env.PORT || 3200; app.listen(port, async () => { try { connectToDB() console.log(`MongoDB Connected http://localhost:${port}`); } catch (err) { console.error('Error during initialization', err); process.exit(1); } }) ``` #### Hono ```typescript import { serve } from "@hono/node-server"; import { cors } from "hono/cors"; import { prettyJSON } from "hono/pretty-json"; import { logger } from "hono/logger"; import { Hono } from "hono"; import { secureHeaders } from "hono/secure-headers"; import { config } from "dotenv"; import connectToDB from "./utils/db"; config(); import users from "./routes/users"; import tasks from "./routes/tasks"; const app = new Hono(); app.use("*", logger()); app.use("*", prettyJSON()); app.use("/api/*", cors(); app.use("/api/*", cors()); app.use("*", secureHeaders()); app.notFound((c) => c.json({ message: "No Route Found for this Endpoint", ok: false }, 404) ); app.route("/api/users", users); app.route("/api/tasks", tasks); serve(app, async (c) => { try { await connectToDB(); console.log(`server running on http://localhost:${c.port}`); app.get("/", (c) => { return c.html("

Hey There!, Welcome to task managers app

"); }); } catch (err) { console.error("Error during initialization", err); process.exit(1); } }); ``` As you can see, Hono takes care of everything from having a built-in logger, handling cors and adding security headers while in Express you have to install separate packages like `morgan`, `cors`, `helmet` to achieve the same functionality. Now I know that these are not large packages and don’t affect the bundle size but if I was a beginner developer and a framework took care of these small yet important things without me having to figure it out on my own, I’ll be more productive doing the actual coding. ## 4. Validations and Middleware **Hono is also better at handling server-side request validations** In Express, we usually define the validation schema in a separate `.validator.ts` file with the `express-validator` package and return a custom message in response to our `.controller.ts` if the body doesn’t pass our validation schema. ```typescript // tasks.validator.ts import { body } from "express-validator"; import { ValidationChain } from "express-validator/src/chain"; import { Priority } from "../enums/priority"; import { Status } from "../enums/status"; export const createValidator : ValidationChain[] = [ body('title') .not() .isEmpty() .withMessage('The task title is mandatory') .trim() .isString() .withMessage('Title needs to be in a text format'), body('date') .not() .isEmpty() .withMessage('Task date is mandatory') .isString() .withMessage('Date needs to be a valid date format'), body('description') .trim() .isString() .withMessage('Description needs to be in text format'), body('priority') .trim() .isIn([Priority.high, Priority.low, Priority.normal]) .withMessage('Priority can only be normal,high or Low'), body('status') .trim() .isIn([Status.completed, Status.inProgress, Status.todo]) .withMessage('Status can only be in progress, completed or Todo'), ] ``` ```typescript // tasks.controller.ts import { Response } from 'express'; import { validationResult } from 'express-validator'; import { Task } from './task.model'; import { MyRequest, ITask } from '../_interfaces'; import { Status } from '../enums/status'; const create = async ( req: MyRequest, res: Response, ): Promise => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // ...rest of the code }; ``` In our Hono app, we use `zod` to handle validations, you can use any other package but I prefer Zod because ~~I love it~~ it integrates very nicely with the `@hono/zod-validator` package of Hono. In Hono, we don’t need to manually send the response, you only need to add the validation middleware and when you’re done, hono will automatically handle the rest. Isn’t it cool! ```typescript // tasks.validator.ts import { z } from 'zod'; import { Priority } from "../enums/priority"; import { Status } from "../enums/status"; export const createTaskValidator = z.object({ title: z.string().min(1, 'The task title is mandatory'), date: z.string().min(1, 'Task date is mandatory'), description: z.string().max(400, "The task description cannot be more than 400 characters"), priority: z.enum([Priority.high, Priority.low, Priority.normal]), status: z.enum([Status.completed, Status.inProgress, Status.todo]), }); ``` ```typescript // tasks.router.ts import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; import { createTaskValidator, } from "../../validators/task"; import { Task } from "../../models/task.model"; router.post( "/", zValidator("form", createTaskValidator), async (c) => { const body = c.req.valid("form"); const user = c.get("user"); // ...rest of the code } ); ``` #### Middleware Hono has built-in middleware for handling both _cookie_ or _jwt-_based authentication. We used the JWT implementation in our app below but you can also check out [**_cookie-based auth_**](https://hono.dev/helpers/cookie) in Hpno In Hono, you can just import the JWT package and sign and verify the JWT token very easily without relying on any third party libraries. In the code below, we are signing the token with the `user._id` property. ```typescript // users.router.ts import { sign } from "hono/jwt"; router.post("/login", zValidator("json", loginValidator), async (c) => { const body = c.req.valid("json"); const { email, password } = body; const user = await User.findOne({ email: email }); await sign({ user._id.toString() }, process.env.JWT_SECRET as string); // ...rest of the code }); ``` Then in our middleware function, we can verify the token and if it’s valid, we set the user on the context object of the hono router and access the user object in any of our routes if we are authenticated. ```typescript // middleware/auth.ts import type { Context, Next } from "hono"; import { verify } from "hono/jwt"; import { User } from "../models/user.model"; export const protect = async ( c : Context, next : Next, ) => { let token: string | undefined; const header = c.req?.header("Authorization") if ( header && header.startsWith('Bearer') ) { // get token from header token = header.split(' ')[1] // check if token exists if (!token || token.length < 500) { c.json('Not Authorized, No Token Available',401) } // verify token const decoded = await verify( token, process.env.JWT_SECRET as string, ) // Get the user ID from the token payload let user = await User.findById(decoded?.id).select( '-password', ); if (!user) { return c.json('No user Found',404); } if (user) c.set("user", user) next() } //...error handling } ``` ```typescript // tasks.router.ts import { IUser } from "../../models/user.model"; type Variables = { user: IUser } // this step satisfies typescript and gives us intellisense throughout our code // if we try to acces user object properties that we set in our protect middleware const router = new Hono<{ Variables: Variables }>() router.get("/", protect, async (c) => { const user = c.get("user"); if (!user) { return c.json({ error: "Not Authorized" }, 401); } } ``` The `protect` middleware is largely similar to middleware in an Express app. In Express, when we extract the token from the request headers, we validate it using the `jwt.verify()` method and assign our user object to `res.locals.user`. Later in our controllers, we access it similarly. ## Production Ready? After evaluating both apps based on the criteria discussed in [_this section_](https://blog.thedevguy.in/articles/express-vs-hono#the-app-should-include), I believe we can confidently tick off all the items below: - Excellent Developer Experience (especially with TypeScript 😍) - Exceptionally performant Router (faster than Express) - Significantly smaller bundle size (thanks to the built-in middleware) - Extremely flexible (deployable on any runtime) > Sure, that’s impressive, but can it handle a _large scale production app?_ Well, that’s entirely up to you. It can perform every function that Express does, strictly adheres to modern web standards, supports all major runtimes, and is extremely potent for handling concurrent requests. So, why not give it a shot? If you’re considering migrating your Express app to Hono, I assure you it won’t cause much trouble. I strongly recommend giving this a try. Until Next Time, **Happy ~~Debugging ~~ Coding👋** *HTML:* https://adityakhare.com/articles/express-vs-hono *Markdown:* https://adityakhare.com/articles/express-vs-hono.md --- # Exploring Useful JavaScript DOM Features **URL:** https://adityakhare.com/articles/exploring-useful-javascript-dom-features **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2023-01-16T06:00:00.000Z **Updated:** 2024-08-26T11:55:49Z --- **Summary:** Today we are dissecting a major element of JavaScript DOM, the global Window Object and the methods that it provides us _One of the key elements of JavaScript DOM is the global Window Object. It provides a wide range of methods and objects that can be incredibly useful for web developers. In this article, we will explore some of the most frequently used features of the Window Object that can greatly enhance your coding experience._ ## 1. setTimeout() The first method we will discuss is `setTimeout()`. This method allows you to execute a function after a specified delay. It takes two arguments: a callback function and a time in milliseconds. Imagine if you have to display a success or error modal after submitting a Form after a certain period or if you are just working on a Project Locally and want to imitate a fetch request from an API. Well, the `setTimeout()` method is the way to go. ```javascript setTimeout(customTheme, 5000); function customTheme() { confirm("Did not like out Themes,Want to Create Your Own ?"); let color = prompt("Just Type the name of color You want"); if (color === null) return; document.body.style.backgroundColor = color; toggleButton.style.display = "none"; headingText.textContent = "custom theme is active now"; } ``` In the given example, after a page is loaded, the customTheme() function is called after a 5-second delay. It displays a confirmation modal and prompts the user to input a colour to change the website's background. If a valid colour is entered, it applies the colour, hides a toggle button, and updates the heading text. ## 2. setInterval() Often, we need to repeatedly execute a function at specific intervals. For such scenarios, \`setInterval()\` comes to our rescue. This method takes a function and the interval at which the function should be executed. But what if you want to stop the function after certain intervals? Well, there's also a method for just that. The `clearInterval()` takes the timer or basically a variable in which the value of `setInterval()` is stored and stops/clears the function inside `setInterval()`. ```javascript let startTime; function startTimer() { timerElement.innerText = 0; startTime = new Date(); setInterval(() => { // the getTimertime() function just increments // time by 1 timerElement.innerText = getTimertime(); }, 1000); } ``` In the above example, the `startTimer()` function initializes a timer. It sets the initial value of the timer element to **0** and starts a `setInterval()` function. This `setInterval()` function updates the timer element every second by calling the `getTimerTime()` function. **NOTE:** However, it is important to note that `setInterval()` may not be precise due to the execution time of the function it calls. To achieve more precise delays at regular intervals, it is recommended to use a nested `setTimeout()` function instead. For a detailed explanation of the differences and use cases, refer to [this article](https://javascript.info/settimeout-setinterval#nested-settimeout). ##
3. scrollTo() One of the most Used window methods. No website today is complete without a Back to Top button. I mean who doesn't love one such button at the footer of a website which when clicked saves you the hazard of using the Scrollbar to get back to the top of the Page? Also, it makes navigating through different sections of your website easy and neat which also increases the user experience. With \`scrollTo()\`, you can implement this functionality with a single line. The method takes two arguments, the X and Y (horizontal and vertical) coordinates of where you want to scroll to on the page. the value cannot be negative. The below example shows a button which takes the user to the top of the Page when clicked. ```javascript btn.onclick = { scrollTo(0,0) // scrollTo(x,y) } ``` Use this with the CSS below for enabling smooth scrolling and you are good to go. ```css html { scroll-behavior: smooth; } ``` ## 4. Window.open() / Window.close() The `open()` method of the Window Object is used to open a new browser window or tab. It takes the following parameters:- - **url (optional):** The URL of the page to be opened. If not specified, an empty window will be opened. - **name (optional):** The name of the window or tab. It can be used as a target for links and form submissions. If not specified, a new window will be opened with a default name. - **features (optional): **A string of window features such as size, position, and toolbar visibility. These features are comma-separated and can be combined. ```javascript function openNewWindow() { window.open("https://www.example.com", "_blank", "width=800,height=600"); } ``` In the above example, the `openNewWindow()` function is called when a button is clicked. It uses the `open()` method to open a new browser window or tab with the URL https://www.example.com The `"_blank`" parameter specifies that the page should be opened in a new tab, and the `"width=800,height=600"` parameter sets the size of the new window. You can also pass an argument as `popup` to it and it will open the new window in a popup-like fashion just like how Google OAuth does it. Similar to the `open()` method `window.close()` method of the Window Object is used to close the current browser window or tab. I know we are talking about methods, but the next one is an object ```javascript function closeWindowAfterFormSubmission(formSubmitted) { if (formSubmitted) { window.close(); } } ``` ## 5. Location Object The location object provides information about the current URL and allows you to navigate to different URLs. It contains properties and methods that can be used to manipulate the browser's location. ####
Properties: - **href:** Returns the complete URL of the current page. ```javascript console.log(window.location.href); // Output: "https://www.example.com/index.html" ``` - **host:** Returns the hostname and port number of the current page. ```javascript console.log(window.location.host); // Output: "www.example.com" ``` - **protocol:** Returns the protocol `(http:// or https://)` of the current page. Can be helpful when managing development and production environments in your code. ```javascript console.log(window.location.protocol); // Output: "https:" if (window.location.protocol === "https:") { signInUser() } else { mockUserSignIn() } ``` - **pathname:** Returns the path or filename of the current page, and can be used to track and perform actions depending on the current pathname of your website. ```javascript console.log(window.location.pathname); // Output: "/contact" if (window.location.pathname === "/home") { animateHeroSection() } ``` - **search:** Returns the query string of the current page. Very important if your code depends on the query parameters of the URL, one common use case is fetching paginated Data from your server depending on which page number you are at. ```javascript console.log(window.location.search); // Output: "?id=123&category=books" // Checking for the 'page' parameter in the query string let urlParams = new URLSearchParams(window.location.search); let page = urlParams.get('page'); if (page) { fetchPosts(page) } else { console.log("ID parameter not found"); } ``` - **hash: **Returns the anchor part of the URL. ```javascript console.log(window.location.hash); // Output: "#section1" ``` #### Methods: - **assign(url):** Loads a new document by setting the href property to the specified URL. helpful in navigating through different pages programmatically. ```javascript function redirectToNewPage() { window.location.assign("https://www.example.com/newpage.html"); } ``` - **reload(): **Reloads the current document, helpful in manually submitting a form or fetching fresh data from the server. ```javascript if(postSuccessfullyDeleted) { window.location.reload(); } ``` - **replace(url): **Replaces the current document with a new one by setting the href property to the specified URL ```javascript function replacePage() { window.location.replace("https://www.example.com/anotherpage.html"); } ``` ## 6. Local Storage This last one is also an Object with very useful methods. How many times have you got your UI changes destroyed (removed) after reloading the Page? All your data with your hard work to make the app work, is Gone. Therefore if you want to persist with the changes you made to your website even after you reload the website, you'll need this object method. Like all Objects \_localStorage\_ stores key-value pairs and almost all object methods work on it like any other plain Object. It mainly uses two methods which are `localStorage.setItem()` and `localStorage.setItem()` to save and retrieve a value from the **localStorage** Object. The Earlier takes key and value as arguments while the latter only takes the key. The keys and values stored in the localStorage object can only be strings. So if you want to store objects within the localStorage you can use the `JSON.stringify()` method below : ```javascript // setting data to localStorage const formState = JSON.stringify(formData.fromEntries()); localStorage.setItem("form-state", formState) // retrieving data from localStorage const defaultFormValues = JSON.parse(localStorage.getItem("form-state")); console.log(defaultFormValues.username); // John ``` The above code sets a value in the local storage by assigning a stringified JSON object to the "form-data" key. To retrieve the data, the JSON.parse() method is used to parse the stored value. In this case, the "name" property of the object is displayed in the console. There's also a `localStorage.removeItem(key)` which removes a specific item from the storage by its key. Additionally, you can also clear the localStorage by calling `localStorage.clear()` to remove all the keys in our localStorage ```javascript // removing specific data by it's key localStorage.removeItem("form-state") // clearing our local storage localStorage.clear() ``` Some common use cases of localStorage include saving formState of huge forms between page reloads, persisting the theme preferences of your website, and sometimes saving an Authorization Token sent from an API to the localStorage and retrieving it later to authenticate the user. I generally don't recommend this and prefer **httpOnly cookies **over localStorage to save my sensitive information Also, remember that local storage only allows you 2MB of maximum storage space, so if your data requirements are larger than that, then you should look for other browser-based storage solutions like [**_indexed DB_**](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) and the [**_Cache API_**](https://developer.mozilla.org/en-US/docs/Web/API/Cache) The **Window** Object offers a plethora of features to enhance JavaScript DOM programming. In this article, we only scratched the surface. By leveraging these features, you can create more interactive and user-friendly web applications. Stay tuned for future articles where we dive deeper into the magical world of the Window Object. Until Next Time, **Happy ~~Debugging ~~ Coding👋** *HTML:* https://adityakhare.com/articles/exploring-useful-javascript-dom-features *Markdown:* https://adityakhare.com/articles/exploring-useful-javascript-dom-features.md --- # How I migrated my NextJS Blog to Astro over a Weekend **URL:** https://adityakhare.com/articles/how-i-migrated-my-nextjs-blog-to-astro-over-a-weekend **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2022-08-09T06:00:00.000Z **Updated:** 2026-11-18T10:08:37Z --- **Summary:** Why you should move your Content Heavy Websites to Astro for Fast load times, easy to maintain, all with zero JS _Migrating a blog from one framework to another can be a daunting task._ _In this blog, I will share my experience of migrating my Next.js blog to Astro and discuss the challenges I faced along the way. _ _I will also provide insights into whether you should consider migrating your blog to Astro or not. So Let's get started..._ ## The Why: First of all, for all the React Haters Out there, I love React and I love NextJS. It’s just that it is overkill for a content-heavy website. But When I built my blog for the first time, I wasn’t aware of this (Poor Me). So I spent about a week just to add a Blog Page to my portfolio Website that too because of the Huge Ecosystem of React Libraries and although it looked good and was functional, it wasn’t the fastest solution. You can still check it out at [https://thedevguy-blog.netlify.app/](https://thedevguy-blog.netlify.app/). But as I’ve said it took a WEEK to Achieve this and it was fast but it wasn’t the fastest. OH, and there were ~~Some~~ **Many** Problems that I’ll discuss in this blog. So Anyway I decided it was time to “break up and move on”. ## The Idea: But Break Up is HARD and Moving On is HARDER. After all, You were accustomed to your Partner and Finding a New One who lets you do the things You Like (pun intended) was not easy. So I started looking for the next best thing. I had been hearing a lot of buzz about the upcoming framework called Astro, which had recently hit version 1.0 Intrigued by its promises of Using **The framework of your choice**, I decided to give it a try, hoping that I could achieve the same functionality but with better performance as Next.js and a simpler setup., it’s a win-win for me. Little did I know that the experience would be fantastic and that I would complete the migration in just a weekend (after spending a week reading the Astro documentation, of course). ## The Challenges with a NextJS Blog: - **NextJS Hates MDX:** Now, that may be too harsh but seriously, NextJS is not very fond of markdown files. It treats them as any other data files, so you have to do SO MUCH mumbo-jumbo to read your markdown files with the `fs` module, remove its extensions, get its raw data, generate the slug for each file from the file names, convert the raw content to valid HTML and then embed it into your MDX components. On top of that, I have to use the `gray-matter` npm package to insert and parse frontmatter (metadata like title, publishedAt etc.) to and from my markdown files. The `reading-time` package to generate reading Time, `next-mdx-remote` and `next-mdx-remote/serialize` to display the generated HTML into my components which I always find totally unnecessary You can look at the disaster below from my `utils/mdx.js` file that I have to create for the above purposes : ```javascript import path from 'path' import fs from 'fs' import matter from 'gray-matter' import readingTime from 'reading-time' import { sync } from 'glob' const articlesPath = 'data/articles' export async function getSlug() { const paths = sync(`${articlesPath}/*.mdx`) const slug = paths.map((path) => { // holds the paths to the directory of the article const pathContent = path.split('/') const fileName = pathContent[pathContent.length - 1] const [slug, _extension] = fileName.split('.') return slug }) return slug } export async function getArticleFromSlug(slug) { const articleDir = path.join(articlesPath, `${slug}.mdx`) const source = fs.readFileSync(articleDir) const { content, data } = matter(source) return { content, frontmatter: { slug, excerpt: data.excerpt, title: data.title, publishedAt: data.publishedAt, readingTime: readingTime(source).text, ...data, }, } } export async function getAllArticles() { const articles = fs.readdirSync(path.join(process.cwd(), 'data/articles')) return articles.reduce((allArticles, articleSlug) => { // get parsed data from mdx files in the "articles" dir const source = fs.readFileSync( path.join(process.cwd(), 'data/articles', articleSlug), 'utf-8' ) const { data } = matter(source) return [ { ...data, slug: articleSlug.replace('.mdx', ''), readingTime: readingTime(source).text, }, ...allArticles, ] }, []) } ``` - **Syntax Highlighting is Hard:** So I use a lot of custom code snippets in my blogs and I want basic Syntax Highlighting for them, but for this purpose, you have to use `remark and rehpye` plugins to get stuff into place, which can take a lot of configuration and time for basic Syntax Highlighting ```javascript import React from 'react' import Head from 'next/head' import {getSlug, getArticleFromSlug} from '../../utils/mdx' import styles from '../../components/Blog.module.scss' import {ProgressBar} from 'scrolling-based-progressbar' import dayjs from 'dayjs' import { MDXRemote } from 'next-mdx-remote' import { serialize } from 'next-mdx-remote/serialize' import rehypeAutolinkHeadings from 'rehype-autolink-headings' import rehypeSlug from 'rehype-slug' import rehypeHighlight from 'rehype-highlight' import 'highlight.js/styles/atom-one-dark-reasonable.css' function BlogPost({post : { source, frontmatter }}) { return ( <> {frontmatter.title}
{/* */}

{frontmatter.title}

{dayjs(frontmatter.publishedAt).format('MMMM D, YYYY')}

) } export default BlogPost // dynamically generate the slugs for each article(s) export async function getStaticPaths() { // getting all paths of each article as an array of objects with their unique slugs const paths = (await getSlug()).map(slug => ({ params: { slug } })) return { paths, // in situations where you try to access a path // that does not exist. it'll return a 404 page fallback: false, } } export async function getStaticProps({ params }) { //fetch the particular file based on the slug const { slug } = params const { content, frontmatter } = await getArticleFromSlug(slug) const optionsObj = { rehypePlugins: [ rehypeSlug, rehypeHighlight, [ rehypeAutolinkHeadings, { behaviour: 'wrap' }, ], ], } const mdxSource = await serialize(content, { mdxOptions: optionsObj, parseFrontmatter: true, }) return { props : { post: { source: mdxSource, frontmatter, }, } } } ``` Even after going through all of this because React has to hydrate the page if you want any kind of interactivity, the performance is not optimal. ## How Astro Solves This : 1. **It’s just JavaScript:** The best thing about Astro is that it’s just plain old JavaScript and not framework-specific. This means that even beginners can write features in normal JS or use any JS library from the thousands of available npm packages, based on their own use case. It also comes with built-in SASS Support which is also good. ```javascript const audio = document.querySelector('audio') const btn = document.querySelector('.toggle') const html = document.body const theme = (() => { if (typeof localStorage !== "undefined" && localStorage.getItem("theme")) { return localStorage.getItem("theme"); } if (window.matchMedia("(prefers-color-scheme: dark)").matches) { return "dark"; } return "light"; })(); if (theme === "light") { html.classList.remove("dark"); } else { html.classList.add("dark"); } btn.addEventListener('click',(e) => { let toggleTheme = localStorage.getItem('theme') if (toggleTheme === "light") { html.classList.add("dark"); localStorage.setItem('theme', 'dark') } else { html.classList.remove("dark"); localStorage.setItem('theme', 'light') } audio.play() }) ``` This is the code to toggle between Light and Dark Mode, Now I know that it’s much more code than if you were using something like React, But it’s still very simple and understandable. 1. **Server-Rendered and Highly Performant:** Astro’s focus on performance was evident from the start. The framework ships No JS by default, resulting in faster page load times and improved overall performance and user experience. 2. **Great Markdown Support:** Astro provides excellent features like syntax highlighting, utility functions, and integration with rehype and remark plugins. This allows leveraging the full power of Markdown, making it easy to create and customize content using familiar syntax and tools. ```javascript // Use Astro.glob() to fetch all posts, and then sort them by date. const posts = (await Astro.glob("./blog/*.{md,mdx}")).sort( (a, b) => new Date(b.frontmatter.pubDate).valueOf() - new Date(a.frontmatter.pubDate).valueOf() ); ``` ``` --- layout: "../../layouts/BlogPost.astro" title: 'What is MVC Architecture in NodeJS' pubDate: 'June 23 2022' description: 'How do I use this architecture to structure my Backend Projects' heroImage: '/images/nodejs.webp' tags : 'nodejs javascript expressjs ' icon : '/images/nodejs.ico' --- ``` The Above code is all we need to get the data from our markdown files including the frontmatter, slugs and reading time with syntax highlighting without any additional packages, configuration or any other hassle. It just works. Now compare this with its alternative NextJS code and see the difference. Minimum code with Maximum Results. That’s Astro for you. 1. **File-Based Routing:** Just like NextJS works with `.js` files through its `pages` folder, Astro does the same for `.md or .mdx` files in its `pages` folder. Simply creating a file makes it a page, providing a convenient and intuitive way to organize content. 2. **Bring Your Own Framework:** Now I haven’t used this feature for this blog, but if you don’t want to BREAKUP with your Favourite Framework, you can bring it Onboard and Astro won’t mind. It’s very understanding of the Developer’s feelings for their favourite framework. You can write your components with them and Astro just converts them to static HTML components and if you want interactivity, you can easily Lazy load them using directives like `client:load` etc. ## Conclusion Migrating my Next.js blog to Astro was a rewarding experience. The framework’s developer experience, performance optimizations, and customization options impressed me from the start. By taking the time to understand Astro’s concepts and following the migration steps, I successfully transformed my blog into a highly performant and customizable static site. If you’re considering migrating your blog or website to Astro, I encourage you to check out [Astro.dev](https://docs.astro.build/en/getting-started/) as now they have also added the `Web Transitions` and `Collections` API in their latest Version (We’ll talk about these later). The Astro documentation and real-world examples will guide you through the process and help you unlock the full potential of this exciting framework. Remember, learning something new can be challenging, but with patience and practice, you’ll be able to make wiser decisions and create exceptional stuff. Emphasize performance, prioritize user experience, and enjoy the journey of exploring different possibilities and approaches to solve Problems. Until Next Time, **Happy ~~Debugging~~ Coding 👋** *HTML:* https://adityakhare.com/articles/how-i-migrated-my-nextjs-blog-to-astro-over-a-weekend *Markdown:* https://adityakhare.com/articles/how-i-migrated-my-nextjs-blog-to-astro-over-a-weekend.md --- # Getting started with CSS Custom Properties **URL:** https://adityakhare.com/articles/css-custom-properties **Author:** Aditya Khare **Source:** [Archives of Aditya Khare - Lessons from a Self-taught Dev's Life](https://adityakhare.com) **Published:** 2022-02-13T05:41:00.000Z **Updated:** 2024-08-27T11:43:27Z --- **Summary:** Do you know that you can use Variables in Vanilla CSS without any preprocessors like SASS or LESS. _Do you know that you can use Variables in Vanilla CSS without any preprocessors like SASS or LESS? Let's Find out How..._ But first, the question arises Why should you even use these Custom properties when You have Preprocessors? Well, Let's Answer that ## Why use CSS Custom Properties over SASS variables 1. Learning SASS for only using Variables is much of an effort, so why do it? 2. No need for a compiler to convert your SASS files into normal CSS. 3. Native, therefore fast and browser compatible. 4. More CSS variables = Less JS Now, let's understand What the heck are these CSS Custom Properties. ## What are Custom Properties If you ever used a Programming language before, you know what a variable is. If not, A variable is something that is defined once, usually at the top of the code, and then can be referenced later anywhere in the code. So Basically, the custom properties are the variables of CSS which minimizes code repetition and saves time. Custom properties are very helpful in large projects. In normal CSS you have to redefine a property like colour or font repetitively for different elements and it is a hazard. ```css /* What you SHOULDN'T do */ body { background : #333; color : white; } h1 { font-size : 3rem; } .element { transition : transform 0.2s linear; } .element:hover { transform : scale(1.2) rotate(45deg); } ``` Well not anymore, Define once, use anywhere from now on. A custom property is written with a preceding `--` sign before its name with no spaces and called(used) with the `var()` keyword. ```css /* What you SHOULD do */ :root { --bg-clr-primary : rgb(80,125,125); --text-clr-primary : white; --font-lg: 3rem; --scale : 1.2; --rotate : 45deg; --full-screen : 100vw; } body { background : var(--bg-clr-primary); color : var(--text-clr-primary); } h1 { font-size : var(--font-lg); } .element { transition : transform 0.2s linear; } .element:hover { transform : var(--scale) var(--rotate); } ``` ## Features of CSS Variables **Flexibility:** One great benefit of Custom properties is that you can structure and combine different variables for more flexibility. Any value you can think of can be converted into a variable. ```css /* combine more than one custom properties together to give your more control */ section { --r : 220; --g : 150; --b : 94; } section div { background-color : rgb(var(--r), var(--g), var(--b)) } ``` 1. **Redefining Your Variables:** An Environment is like a world within itself for a code block. The Code within an environment doesn't care anything about anything outside its environment and obeys the rules of its own Environment. With CSS variables, You can also redefine or change the value of a custom property with a new value within a specific element and it will work with that value in its local environment instead of the globally defined custom property. ```css /* Redefine custom properties anywhere you want */ /* create your own color scheme */ section { --r : 220; --g : 150; --b : 94; } section div { background-color : rgb(var(--r), var(--g), var(--b)) } /* THIS WORKS */ section .container { --g : 139; --b : 53; background-color : rgb(var(--r), var(--g), var(--b)) } ``` 1. **Using** **`calc()`** **function with your variables:** The `calc()` function can perform basic mathematical operations in CSS. Make your whole layout responsive by using it with predefined custom properties which helps in structuring the sizes of your elements. ```css /* Calculate and adjust your layout sizes */ /* With the help of predefined properties and calc() function */ h1 { font-size : var(--font-lg); } /* All size units just works with calc() */ h2 { font-size : calc(var(--font-lg) / 2); } .parent { width : var(--full-screen); } .child { width : calc(var(--full-screen) - 6rem) } ``` **This blog was just an introduction to the awesomeness of CSS variables.** There are a whole lot of things you can achieve with the custom properties and with your creativity, so keep practising with them. Until Next Time, **Happy ~~Debugging~~ Coding👋** *HTML:* https://adityakhare.com/articles/css-custom-properties *Markdown:* https://adityakhare.com/articles/css-custom-properties.md ---