Skip to main content

Claude Code vs OpenCode

· 10 min read
Guster
Principal Engineer

image

Introduction​

For the past year I have done most of my coding inside a terminal agent. I started with Claude Code because it was the first one that felt like it understood a whole repository, then I moved to OpenCode, now on version 2, for the model freedom. Today I keep both installed and reach for each one depending on the job.

This is not a benchmark post. I am not going to compare task completion scores or token throughput. This is what each tool feels like after living with it, the features I now depend on, and the parts that still annoy me.

The short version​

Claude CodeOpenCode
Made byAnthropicSST, open source
ModelsClaude onlyAny provider, switch mid-session
InterfaceTerminal, IDE, web, mobileTerminal, desktop, server and SDK
Auto modeAuto-accept edits, plan mode, bypassPermission rules per tool and agent
Subagents.claude/agents.opencode/agent
HooksLifecycle hooksPlugins in JS or TS
CostSubscription or APIFree tool, you pay the model
Best forDeep work on large codebasesModel flexibility and scripting

What both get right​

Both tools are terminal first. They read files, run commands, edit code, and keep going until the task is done or they get stuck. Both support MCP servers, project memory files, custom slash commands, and subagents. If you have used one, the mental model transfers to the other almost completely.

The difference is in the details and the philosophy behind them.

Claude Code: the polished default​

Auto mode, plan mode, and permissions​

The feature I miss most when I am not using Claude Code is the permission cycle. Shift+Tab moves between normal mode, auto-accept edits, and plan mode. In auto-accept, the agent edits files without asking, but still asks before running commands. Plan mode flips it around: the agent reads, explores, and writes a plan, but cannot touch anything.

I use plan mode at the start of every unfamiliar task. It is much cheaper to correct a plan than to correct 300 lines of code.

For containers and throwaway branches there is --dangerously-skip-permissions, which removes the prompts entirely. I only run that inside a sandbox with no credentials.

The nice thing is that these modes are visible. I always know which one I am in, and switching is one keystroke.

Subagents​

Claude Code lets me define subagents as markdown files. Each one gets its own context window, its own tool list, and optionally its own model.

---
name: code-reviewer
description: Reviews a diff for bugs, regressions, and missing tests. Use after a feature is implemented.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are a strict code reviewer. Read the diff, list findings by severity, and do not edit files.

The main agent delegates through the Task tool. I use this for reviews, for exploring a new codebase, and for running the same investigation in parallel. The isolation is the point: a subagent can read fifty files without polluting the main conversation.

Hooks​

Hooks are the feature that makes Claude Code feel like a real tool rather than a chat window. You can run a command before or after a tool call, when the agent stops, when a session starts, and so on. If the hook exits with code 2, the agent is blocked and sees the error.

{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}

That one snippet removes an entire class of "the agent forgot to format" problems. I also use a hook to run the linter after edits, and another to append a line to a log whenever a session ends. Hooks are deterministic, and determinism is what agents usually lack.

Memory and commands​

CLAUDE.md is loaded into every session. I keep a short one at the repo root with build commands, conventions, and things the agent should never touch, plus a longer one in ~/.claude/CLAUDE.md with my personal preferences. Custom commands in .claude/commands/ turn repeated prompts into /review, /ship, and /explain.

The ecosystem is the strongest part. The same agent runs in the terminal, in VS Code and JetBrains, in the browser, and on my phone. I can start a task on my laptop, close it, and check on it later. There is also an SDK if I want to build my own automation on top.

Claude Code: what I don't like​

The biggest one is the lock-in. You can switch between Claude models with /model, and you can run through Bedrock or Vertex, but you cannot ask for GPT or Gemini in the middle of a session. If Anthropic has a bad week, so do I.

The second is cost and limits. The subscription is great value until you hit the usage window, and then you are either waiting or paying API rates. I have learned to watch context size and to use subagents partly for cost reasons, not just for isolation.

Third, it is closed source. When a hook misfires or the TUI does something strange, I can report it, but I cannot read the code or patch it. For a tool I use every day, that bothers me more than I expected.

Finally, configuration is JSON heavy. Hooks, permissions, and settings all live in nested JSON, and a typo fails quietly. It works, but it is not pleasant to maintain.

OpenCode: the open one​

Model switching, done properly​

This is the reason I installed OpenCode in the first place. You can switch models mid-session with /models, and more importantly you can assign different models to different agents. Planning runs on a strong model, implementation runs on a cheaper one, and the title generator runs on something tiny.

{
"$schema": "https://opencode.ai/config.json",
"model": "anthropic/claude-sonnet-5-5",
"small_model": "deepseek/deepseek-v4.1-flash-1017",
"agent": {
"review": {
"description": "Reviews changes for bugs and missing tests",
"mode": "subagent",
"model": "openai/gpt-5",
"tools": { "write": false, "edit": false }
}
}
}

The exact model ids change every few months, so run opencode models and use whatever is current.

Provider setup is one command, and keys live in one place. If a new model drops, I add the provider and use it the same day. If I want to keep sensitive code local, I point it at Ollama and nothing leaves the machine. That flexibility is worth a lot to me.

Agents and subagents​

OpenCode ships with two primary agents, build and plan, and you switch with Tab. Custom agents are markdown files with frontmatter, just like Claude Code, but the config surface is broader: model, temperature, prompt, tools, and permissions can all be set per agent.

---
description: Reviews changes for bugs and missing tests
mode: subagent
model: anthropic/claude-sonnet-4-5
tools:
write: false
edit: false
---

You review diffs. Report findings by severity. Do not edit files.

Subagents run in their own session. In OpenCode I can launch several in parallel, and recent versions can run them in the background while I keep working. This is where the multi-model design pays off: I can have three reviewers on three different models and compare what each one catches.

Permissions as configuration​

Instead of a mode toggle, OpenCode asks you to declare rules. You can allow, ask, or deny per tool, and bash rules can match command patterns.

{
"permission": {
"edit": "allow",
"bash": {
"*": "ask",
"git status": "allow",
"git diff*": "allow",
"rm *": "deny"
}
}
}

It is more work to set up than Shift+Tab, but it is also more precise. I can let the agent edit freely while still stopping it from force pushing.

Session tabs​

The feature that surprised me most in OpenCode 2 is session tabs. I can keep several sessions open at once and switch with Ctrl+Tab and Ctrl+Shift+Tab, jump straight to a numbered tab with Ctrl+1 through Ctrl+0, close one with Ctrl+X then W, and reopen it with Ctrl+Shift+T. The tab strip can sit horizontally or vertically, and the labels can show a status dot or a number.

I use this more than I expected. One tab runs the main task, another is a second feature I am poking at, and a third is a scratch session for a question I do not want to pollute the main context with. Before tabs I was either opening another terminal or losing the thread. It is a small feature, but it changes how I work.

The rest of the toolbox​

OpenCode runs a server and a client, which means the TUI, the desktop app, and any script share the same session. I can start a session in the terminal, then attach from the desktop app. There is an SDK, a headless opencode run mode, and a share link for handing a session to a teammate.

It also wires up your language server. Diagnostics come back to the agent automatically, so it sees type errors without running a full build. Plugins are plain JS or TS, so I can hook into tool execution without learning a new config language. And each session can be moved into its own git worktree, which is the cleanest way I have found to run two agents on the same repo without them stepping on each other.

OpenCode: what I don't like​

OpenCode moves fast, and fast means churn. Config keys get renamed, behaviour changes between releases, and occasionally a provider integration breaks for a day. I pin versions on machines where I care about stability.

The configuration surface is large. Claude Code has a handful of concepts, while OpenCode has a config file with dozens of options. That is power, but it is also a weekend of reading docs before it feels right.

Quality depends heavily on the model you plug in. Claude Code is tuned around Claude, and the prompts, tools, and defaults all assume it. OpenCode has to work with everything, so a weak model produces a weak agent. The tool will not save you from a bad model choice.

Finally, there is no single throat to choke. When something breaks, it might be the tool, the provider, the model, or the MCP server. Debugging that chain takes longer than filing a ticket with one vendor.

How I split the work​

  • Claude Code for long, autonomous tasks on a large codebase. Plan mode, hooks, and a model trained alongside the harness still give me the best results when I want to hand over a whole feature.
  • OpenCode for everything else. Quick fixes, model comparisons, local models, scripted runs in CI, and any task where I want a specific model or provider.
  • Both for reviews. I like running a second agent on a different model and diffing the findings.

Which one should you use​

  • If you want the most polished experience and you are happy to pay for Claude, use Claude Code. It is the easiest recommendation for a team that just wants results.
  • If you care about model choice, local inference, open source, or scripting, use OpenCode. It is the better tool for people who like to own their setup.
  • If you are unsure, start with Claude Code to learn the workflow, then try OpenCode for a week. The concepts transfer, and you will know quickly which trade-off you prefer.

Closing thoughts​

I do not think one tool wins. Claude Code is the better product, in the sense that it is more coherent and more polished. OpenCode is the better platform, in the sense that it lets me decide which model runs, where it runs, and how it is wired into my workflow.

The gap between them is closing in both directions. Claude Code keeps adding flexibility, and OpenCode keeps smoothing its rough edges. That is good for all of us. The real winner is the developer who can switch tools without relearning how to think.

Test local with k3d

· 7 min read
Guster
Principal Engineer

image

Introduction​

Every Kubernetes manifest I write eventually ends up on EKS. For a long time I tested those manifests by applying them straight to a shared dev cluster. It worked, but the feedback loop was painful. A wrong selector meant waiting for a rollout, a bad probe meant reading events on a remote node, and every experiment left a small mess behind.

So I started looking for a local cluster that was fast enough to create per task and close enough to EKS to trust. I tried kind, then minikube, and finally k3d. k3d is the one I kept.

This is not a feature-by-feature review of every local Kubernetes tool. It is the setup I use, the parts that matter to me, and why k3d became my default.

The short version​

k3dkindminikube
Runtimek3s in DockerKubernetes in DockerVM or container
Start timeSecondsSecondsA minute or more
Multi-node--agents NConfig file--nodes N
Local registryBuilt inManualAddon or manual
IngressTraefik includedInstall manuallyAddon
Best forApp dev and CIUpstream Kubernetes testingLearning and addons

What I wanted from a local cluster​

  • Fast enough to create and delete per task.
  • More than one node, so scheduling, affinity, and rolling updates mean something.
  • A registry that does not require pushing to a cloud account.
  • Ingress on localhost, so I can test real URLs.
  • A small enough footprint to run in CI.
  • Close enough to EKS that a manifest which works locally has a good chance of working there.

Why k3d​

k3d runs k3s inside Docker. k3s is a CNCF conformant Kubernetes distribution, so the API and the core objects behave the way I expect. The difference is packaging: one lightweight binary, a small control plane, and a load balancer container in front.

Creating a cluster with two agents is one command:

k3d cluster create dev \
--agents 2 \
--port "8080:80@loadbalancer" \
--port "8443:443@loadbalancer"

The cluster is ready in seconds. The port flags map localhost to the load balancer, so an Ingress on port 80 is reachable at http://localhost:8080.

Getting my image into the cluster​

This is the part that usually annoys me with local clusters. k3d has image import:

docker build -t my-api:dev .
k3d image import my-api:dev -c dev

The Deployment can then use my-api:dev with imagePullPolicy: IfNotPresent. No registry, no push, no credentials.

If I want a real registry, k3d can create one:

k3d registry create registry.localhost --port 5000
k3d cluster create dev --registry-use k3d-registry.localhost:5000

I use the registry when I am testing Helm charts or CI pipelines that expect to pull by tag. For day to day, image import is faster.

A config file I can commit​

Typing flags gets old, so I keep a k3d-config.yaml in the repo:

apiVersion: k3d.io/v1alpha5
kind: Simple
metadata:
name: dev
servers: 1
agents: 2
ports:
- port: 8080:80
nodeFilters:
- loadbalancer
- port: 8443:443
nodeFilters:
- loadbalancer
k3d cluster create --config k3d-config.yaml

Now the cluster shape is versioned with the app, and a new teammate gets the same setup with one command.

Testing the manifests​

My loop is boring, which is the point:

kubectl apply -f k8s/
kubectl rollout status deployment/my-api
curl http://localhost:8080/health

If a probe is wrong, I see it in seconds. If a selector does not match, kubectl describe is local and instant. If I break the cluster, I delete it and start again:

k3d cluster delete dev

That last command is the reason I stopped using a shared dev cluster for manifest work. I can be careless locally in a way I never could on a cluster someone else also uses.

What k3d is not​

k3d is not EKS. There are no IAM roles for service accounts, no ALB ingress controller, no EBS CSI driver, no VPC CNI, and no managed node groups. The defaults are different too: Traefik instead of ALB, ServiceLB instead of a cloud load balancer, and local-path storage instead of EBS.

If I am testing IAM, load balancer annotations, or storage classes, I still need a small EKS dev cluster. I use k3d for the parts that are application behaviour: deployments, services, config maps, secrets, probes, jobs, ingress rules, and rolling updates.

k3d also needs a Docker daemon. Podman support exists, but I stick to Docker because that is what my CI runners already have.

k3d vs kind vs minikube​

kind is excellent. It runs upstream Kubernetes in Docker and it is the tool I reach for when I want to test something close to the source, like a new Kubernetes version or an admission controller. The trade-off is setup: no ingress controller, no registry, and multi-node clusters need a config file. I can build all of that, but I would rather not rebuild it for every project.

minikube is the most feature-complete of the three. It has addons for ingress, dashboards, metrics, and more, and it is a great way to learn Kubernetes. It is also the heaviest. A VM or container driver, more memory, and a slower start make it a worse fit when I want a cluster for a twenty-minute task. Multi-node works, but it is not the default experience.

k3d sits in the middle and wins on workflow. Multi-node is a flag. Ingress is already there. A registry is one command. Image import is one command. The cluster starts in seconds and deletes cleanly. For application development and CI, that combination is hard to beat.

How I use it day to day​

  • One cluster per project, named after the project.
  • k3d cluster stop at the end of the day, k3d cluster start in the morning, and k3d cluster delete when the branch is merged.
  • A k8s/ directory with Kustomize overlays: local for k3d, prod for EKS. The local overlay only changes the image and points the Ingress host at localhost.
  • Integration tests in CI: create the cluster, import the image, apply the manifests, run the tests, delete the cluster.
  • Pin the k3s image in the config so a new release does not change behaviour mid-sprint.
image: rancher/k3s:<version>-k3s1

What I don't like​

  • Docker dependency. When Docker Desktop is unhappy, k3d is unhappy.
  • Defaults differ from EKS, so some manifests need a local overlay. Traefik versus ALB is the usual one.
  • Image import is manual. Forget it, and you get ImagePullBackOff for a tag that exists locally. I have done this more than once.
  • Networking through the load balancer container can be confusing when a service is not reachable. k3d node list and docker logs are part of the debugging story.
  • Version skew. k3s is not EKS, and a feature that works on one may not exist on the other.
  • Resource use. Two agents plus a server is still three containers plus the load balancer. On a small laptop, one agent is enough.

Which one should you use​

  • k3d if you want a fast, disposable cluster for app development and CI, with multi-node and ingress without extra setup.
  • kind if you are testing Kubernetes itself, need upstream parity, or already have a kind-based workflow.
  • minikube if you are learning Kubernetes and want addons and a dashboard in one command.
  • A real EKS dev cluster for IAM, load balancers, storage classes, and anything else that depends on AWS.

Closing thoughts​

k3d is my preferred local cluster because it removes the friction I actually care about: creating a cluster, getting my image in, reaching it on localhost, and deleting it when I am done. It is not a replacement for EKS, and I do not pretend it is. It is the place where I catch the boring mistakes before they cost me a rollout on the real cluster.

Building a MFE with AWS Cloudfront + S3

· 5 min read
Guster
Principal Engineer

image

Building a Monorepo MFE with Nx and AWS CloudFront + S3

Introduction​

Micro Frontend (MFE) architecture has become a popular approach for scaling frontend applications. By splitting the frontend into independent modules, teams can work on different parts of the app simultaneously. In this blog, I'll walk you through how I built a monorepo MFE using Nx, AWS S3, and CloudFront.

This setup consists of:

  • Shell App (Host application)
  • Shop App (Remote MFE in a separate repo as a Git submodule)
  • About App (Remote MFE in the main monorepo)

I'll cover how to:

  1. Scaffold an Nx-based MFE project
  2. Configure Git submodules for the remote shop app
  3. Build and deploy the apps to an AWS S3 bucket & CloudFront

Architecture​

Overall MFE architecture:​

image

MFE Git repository structure:​


Step 1: Setting Up an Nx Monorepo​

First, create a new Nx workspace configured for an Angular MFE setup:

npx create-nx-workspace nx-monorepo-mfe --preset=apps
cd nx-monorepo-mfe

Add the MFE Module Federation plugin:

nx add @nx/angular

Now, generate the shell and remote apps:

nx g @nx/angular:host apps/shell

nx g @nx/angular:remote apps/about --host=shell

The shell app serves as the main host, dynamically loading remote apps (about and shop).


Step 2: Add a Remote App about​

Let's generate our first remote app for the About page:

nx g @nx/angular:remote apps/about --host=shell

Verify that it is registered in the shell's module-fedration.config.ts.

const config: ModuleFederationConfig = {
name: 'shell',
remotes: ['shop', 'about'],
};

Step 3: Adding a Remote shop App as a Git Submodule​

Since the shop app resides in a separate repository, we’ll add it as a Git submodule.

3.1 Generate shop remote app​

Similar to how we generated about app above, let's generate the shop remote app with Nx's Angular generator:

nx g @nx/angular:remote apps/shop --host=shell

This will generate a remote app shop in apps/shop/ directory and register it in the shell's module-federation.config.ts.

const config: ModuleFederationConfig = {
name: 'shell',
remotes: ['shop'],
};

3.2 Initialize shop Git submodule repository​

Let's initialize the remote app apps/shop as another Git repository.

cd apps/shop
git init
git remote add origin <GIT_REPO_URL_FOR_SHOP>

Navigate to the root of the monorepo and add it to the .gitmodules

git submodule add <GIT_REPO_URL_FOR_SHOP> apps/shop

# this track the changes for the latest commit of `shop` repo.
git add apps/shop

Step 4: Create an AWS S3 Bucket​

In order to host our MFE app, we need to enable the static site hosting in the S3 bucket.

Sample terraform script:

# ==================== S3 ====================
resource "aws_s3_bucket" "mfe_app" {
bucket = "<your_bucket_name>"
}
resource "aws_s3_bucket_policy" "mfe_app_policy" {
bucket = aws_s3_bucket.mfe_app.id
policy = jsonencode(
{
Version = "2012-10-17"
Statement = [
{
Sid = "PublicReadGetObject"
Action = "s3:GetObject"
Effect = "Allow"
Principal = "*"
Resource = "${aws_s3_bucket.mfe_app.arn}/*"
},
]
}
)
}

# Enable static website hosting
resource "aws_s3_bucket_website_configuration" "mfe_app" {
bucket = aws_s3_bucket.mfe_app.id

index_document {
suffix = "index.html"
}

error_document {
key = "error.html"
}
}
resource "aws_s3_bucket_public_access_block" "mfe_app" {
bucket = aws_s3_bucket.mfe_app.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}

Step 5: Building and Deploying to AWS S3​

Each app needs to be built and deployed to S3 buckets.

First, let's build the apps. This will generate the built arfifacts in dist/apps/.

nx build shell
nx build about
nx build shop

# alternatively, you can build all with:
nx run-many -t build

Then deploy each app to S3 whenever necessary.

aws s3 sync dist/apps/shell s3://my-mfe-bucket/shell --delete
aws s3 sync dist/apps/about s3://my-mfe-bucket/about --delete
aws s3 sync dist/apps/shop s3://my-mfe-bucket/shop --delete

Step 6: Setting Up CloudFront​

Now that we have deployed our MFE app to the S3. Technically we can already access it directly via the S3 public url, eg: http://<your-bucket-name>.s3-website-ap-southeast-1.amazonaws.com, but the redirection will not work properly when reloading the page.

Hence, we need to setup a CloudFront distribution and configure it to serve from the S3 bucket:

Terraform script:

resource "aws_cloudfront_origin_access_control" "oac" {
name = "my-mfe-s3-access-control"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}

# CloudFront distribution
resource "aws_cloudfront_distribution" "mfe_cloudfront" {
# our MFE shell app is hosted in a S3 directory instead of root /, we need to tell CF where to look for index.html
default_root_object = "shell/index.html"
enabled = true

origin {
# replace `<your_s3_bucket>` with your bucket name
domain_name = "<your_s3_bucket>.s3-website-ap-southeast-1.amazonaws.com"
origin_id = "my_s3_origin"
origin_access_control_id = aws_cloudfront_origin_access_control.oac.id
}

custom_error_response {
error_caching_min_ttl = 10
error_code = 403
response_code = 200
response_page_path = "/shell/index.html"
}
custom_error_response {
error_caching_min_ttl = 10
error_code = 404
response_code = 200
response_page_path = "/shell/index.html"
}

default_cache_behavior {
allowed_methods = [
"GET",
"HEAD",
]
cached_methods = [
"GET",
"HEAD",
]
target_origin_id = "my_s3_origin"
viewer_protocol_policy = "redirect-to-https"
}

restrictions {
geo_restriction {
restriction_type = "none"
}
}

viewer_certificate {
cloudfront_default_certificate = true
}
}

This ensures requests are routed correctly to the MFE remotes.


Summary​

By following these steps, we:

  • ✅ Created an Nx monorepo with an MFE setup
  • ✅ Integrated a Git submodule for the shop remote app
  • ✅ Built and deployed each MFE to AWS S3
  • ✅ Used AWS CloudFront to route requests dynamically

This architecture enables scalability, independent deployments, and improved maintainability for micro frontends.

.NET Unit Test with xUnit

· 3 min read
Guster
Principal Engineer

image

Introduction

Unit testing in a .NET project requires a slightly different approach compared to other web frameworks like Spring Boot, Ruby on Rails, Node.js, or Laravel.

Typically, in these frameworks, we integrate a unit testing library—such as jest for Node or rspec for Rails—directly into the source project via the package manager manifest (package.json or Gemfile). These package managers often allow you to specify the environment for installing dependencies (e.g., npm install --dev).

In .NET, however, this isn't the case. To integrate unit tests, we need to restructure the project.

For example, assuming you have an existing .NET project with this structure.

/my-todo-app
my-todo-app.sln
/src
MyClass.cs

You will need to restructure the project similar to

/my-todo-app
my-todo-app.sln
/src
MyClass.cs
my-todo-app.csproj
/tests
MyClassTests.cs
test.csproj

Ensure there's no nested .csproj structure—that is, avoid placing a .csproj file inside a parent folder that already contains another .csproj. This prevents the error Duplicate global::System.Runtime.Versioning.TargetFrameworkAttribute.

Example of a well-structured .NET project

MySolution/
│
├── MySolution.sln # Solution file
│
├── src/ # Source code directory
│ ├── MyApp/ # Main application project
│ ├── MyApp.csproj # Project file for MyApp
│ ├── Program.cs # Entry point for the application
│ ├── Startup.cs # Configuration and services setup
│ ├── Controllers/ # MVC or API controllers
│ │ └── HomeController.cs # Example controller
│ ├── Models/ # Application models
│ │ └── UserModel.cs # Example model
│ └── Services/ # Business logic services
│ └── UserService.cs # Example service
│
└── tests/ # Test projects directory
├── MyApp.Tests/ # Unit test project for MyApp
├── MyApp.Tests.csproj # Project file for unit tests
├── UserServiceTests.cs # Unit tests for UserService
└── HomeControllerTests.cs # Unit tests for HomeController

Create a unit test

Now let's dive into how it works. Assume we have a service class AuthService that's responsible for generating and decoding JWT tokens.

public class AuthService
{
public string GenerateJwtToken(User user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("jwt_secret_key");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(
[
new Claim("id", user.Id.ToString())
]),
Issuer = "john",
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}

public JwtPayload DecodeJwtToken(string token)
{
var handler = new JwtSecurityTokenHandler();
var payload = handler.ReadJwtToken(token).Payload;
return payload;
}
}

Create a test class AuthServiceTest under /tests directory

public class AuthServiceTest
{
[Fact]
public void TestGenerateJwtToken()
{
var user = new User { Id = 1, Email = "lorem@ipsum.com" };
var authService = new AuthService();
var token = authService.GenerateJwtToken(user);
var decodedPayload = authService.DecodeJwtToken(token);

// assert that the JWT token is not null
Assert.NotNull(token);

// assert that the claim "id" is as expected
Assert.Equal("1", decodedPayload["id"].ToString());
}
}

Start testing

Now that we have created a sample test, let’s run it.

  • Run the following command to run all unit tests in the project

    dotnet test
  • To run a specific test, use the --filter option. For more advanced filtering techniques, visit the official documentation.

    dotnet test --filter "AuthServiceTest"
  • A summary of the test results will be shown

    Starting test execution, please wait...
    A total of 1 test files matched the specified pattern.

    Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: < 1 ms - test.dll (net8.0)

Summary

Unit testing is an essential practice in software development, and xUnit provides a robust framework for .NET developers to implement effective tests. By following the structure and examples outlined in this guide, you can create comprehensive unit tests for your .NET applications. Remember that regular testing helps catch bugs early, improves code quality, and increases confidence in your codebase. As you become more familiar with xUnit, you'll find it an invaluable tool in your development process.

Speedrun .NET + Angular

· 4 min read
Guster
Principal Engineer

image

Introduction

Recently, I had an initial interview with a new company that uses Angular and .NET as its tech stack. Frankly, these two frameworks are pretty unfamiliar to me. I used to work with Angular.js back when it was still v1, which was about 8 years ago. I remember it was renamed to just Angular starting from v2, and now it's already at v18.

What about .NET? Even worse, I have never used it in my entire life! In fact, I don't know C# at all. Though I've heard a lot about it and that it's similar to Java.

Long story short, regardless of whether I advance to the next interview, I decided to take this as an opportunity to learn some new skills. However, I don't want to spend too much time learning. So, I decided to start a speed run on learning .NET and Angular.

How I learn

How I usually learn a new framework or programming language is by building a sample project. Here are a few pros of this approach:

  • Less boring - You get to see your half-baked product evolve while going through the tutorial.
  • Learn based on the features you need - It takes time to learn everything, especially with a complex framework like .NET. It's better to learn as you go. For example, if you need user authentication or a database migration.
  • Feels accomplished once the sample project is done and deployed for showcasing!

I have shared some of the notable points I learned from these frameworks here:

A Todo Project

And so, I decided to build a simple Todo task list. This Todo will contain the following features and acceptance criteria:

  • A login page for user authentication
  • Users can create, read, update, and delete a collection (a group of tasks)
  • Users can create, read, update, and delete a task within a collection
  • A main page with a two-pane layout: the left pane shows a list of collections, and the right pane shows the selected collection’s tasks
  • Users must be authenticated to view the main page
  • Basic UI styling (tailwind for the rescue!)
  • Logout functionality

Deployment

Now that I have finished building the API and web app, I want to deploy them somewhere to showcase if needed. Since I already have AWS, I decided to deploy there.

I want it fast and simple, so here’s what I did:

  • Hosted the Angular app on an S3 bucket as a static site
  • Dockerized the .NET API and deployed it to an EC2 instance
  • Created a Postgres instance in RDS

I used Terraform to ease the process of provisioning these resources. Here’s a sample script.

# VPC, subnets, internet gateway, route table and security groups provisioning
# ...

# ==================== RDS ====================
resource "aws_db_instance" "my_rds" {
allocated_storage = 20
engine = "postgres"
engine_version = "16.4"
instance_class = "db.t3.micro"
db_name = "mydatabase"
username = "username"
password = "password"
vpc_security_group_ids = [aws_security_group.rds_sg.id]
db_subnet_group_name = aws_db_subnet_group.my_db_subnet_group.name
skip_final_snapshot = true
publicly_accessible = false
}
resource "aws_db_subnet_group" "my_db_subnet_group" {
name = "my-db-subnet-group"
subnet_ids = [
aws_subnet.private_subnet_a.id,
aws_subnet.private_subnet_b.id
]
}

# ==================== EC2 ====================
resource "aws_instance" "dotnet_todo_instance" {
ami = "ami-0a6b545f62129c495"
instance_type = "t2.micro"
subnet_id = aws_subnet.public_subnet_a.id
vpc_security_group_ids = [aws_security_group.ec2_sg.id]
tags = {
Name = "dotnet-todo-ec2"
}
}

# ==================== S3 ====================
resource "aws_s3_bucket" "dotnet_todo_web" {
bucket = "dotnet-todo-web"
}
resource "aws_s3_bucket_policy" "dotnet_todo_web_policy" {
bucket = aws_s3_bucket.dotnet_todo_web.id
policy = jsonencode(
{
Version = "2012-10-17"
Statement = [
{
Sid = "PublicReadGetObject"
Action = "s3:GetObject"
Effect = "Allow"
Principal = "*"
Resource = "${aws_s3_bucket.dotnet_todo_web.arn}/*"
},
]
}
)
}

Result

Screenshot 2024-08-19 at 10.34.42 PM.png

Screenshot 2024-08-19 at 10.34.27 PM.png

Concluding Thoughts

Overall, it took me roughly one week to learn Angular, .NET, and complete the project. From a developer's perspective, the experience was quite smooth and easy. I found Angular's opinionated structure to be particularly beneficial. Its out-of-the-box common libraries saved me a significant amount of time that I would have otherwise spent searching for third-party solutions. This allowed me to focus more on building the actual features of my project rather than dealing with setup complexities.

When it comes to .NET, although I don’t particularly like C#’s Pascal-case naming conventions and its syntax formatting, I must admit that .NET is very easy to set up, develop, and build. I found the CLI and generators to be especially helpful tools that streamlined the development process. These tools provided a robust foundation, making it easier to manage and organize the codebase efficiently.

I built a simple todo for this project, but the learning experience has inspired me to explore more complex projects using Angular and .NET. I am definitely going to start building more with Angular and .NET in the future. The combination of these frameworks provides a powerful and efficient development environment that I am excited to continue exploring.

My Angular 18 crash course

· 5 min read
Guster
Principal Engineer

image

Introduction​

Angular is a powerful and versatile web application framework that enables developers to create robust, high-performance applications with ease. It provides a rich set of tools and features designed to streamline the development process and enhance code maintainability. By leveraging Angular's component-based architecture, developers can build scalable and modular applications that are both efficient and easy to maintain.

In this guide, I’ll briefly walk you through the essential steps to set up and run an Angular project, giving you a solid foundation to start your journey into Angular development. From installation and project creation to understanding the core concepts.

Installation​

Prerequisites​

  • Node.js - v18.9.1 or newer
  • CLI

Install Angular CLI​

npm install -g @angular/cli

For more details, follow the installation guide on the official documentation.

CLI Commands​

  • ng new <project-name> - Create a new project

  • ng generate - Generate Angular resources

    • ng generate component <name> - Generate component
    • ng generate service <name> - Generate service class
    • ng generate class <name> - Generate a class
    • ng generate directive <name> - Generate a directive
    • ng generate interceptor <name> - Generate an interceptor
    • ng generate guard <name> - Generate a authentication guard
  • npm start - Start local development

  • npm run test - Run unit tests

  • npm run build - Build a project

Create a new project​

To create a new project, run command ng new <project_name>, eg. ng new my-todo-app, this will generate a new project with the following file structure. The source codes will be inside the /src directory.

.
├── README.md
├── angular.json
├── dist
├── package-lock.json
├── package.json
├── public
├── server.ts
├── src
├── tsconfig.app.json
├── tsconfig.json
└── tsconfig.spec.json

Component​

When we generate a Angular component with ng generate component, the CLI will scaffold the following files. Example:

src/app/
├── app.component.css
├── app.component.html
├── app.component.spec.ts
├── app.component.ts

These files are self-explanatory: the .css file contains the CSS styling, while the .html file defines the component's UI, and .spec for unit test.

Alternatively, we can use the template and styles attributes in the @Component decorator to include CSS and HTML code directly in app.component.ts, creating a single-file component.

Component with external template and CSS:

@Component({
selector: 'app-root',
standalone: true,
imports: [],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {}

Single-file component:

@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `<div>hello world</div>`,
styles: {...}
})
export class AppComponent {}

A component can be used in a template with its selector. For example, if you want to use a custom component <my-custom-button>in this component, you first need to import it with imports: [MyCustomButton]

@Component({
selector: 'app-root',
standalone: true,
imports: [MyCustomButton],
styleUrl: './app.component.css',
template: `
<my-custom-button></my-custom-button>
`,
})
export class AppComponent {}

Dependency Injection (DI)​

Make a class Injectable​

Dependency Injection (DI) is a core concept in Angular, widely used throughout the application. DI allows us to incorporate dependencies into classes while Angular manages their lifecycle.

To make a class injectable, decorate it with the @Injectable decorator. For instance, consider a service class named AuthService.

@Injectable({ providedIn: 'root' })
class AuthService {}

The providedIn: 'root' option tells Angular to provide AuthService at the application's root level, allowing it to be injected into all other classes. This approach enables Angular and JavaScript code optimizers to effectively remove unused services—a process known as "tree-shaking."

Injecting a dependency​

Once we have made a class injectable with @Injectable, there are two ways we can use it in other classes.

  1. Inject in the constructor

    @Component({ … })
    class AppComponent {
    constructor(private service: AuthService) {}
    }
  2. Inject with the built-in inject method

    @Component({ … })
    class AppComponent {
    private service = inject(AuthService);
    }

💡 Tips: Angular CLI provides a quick way to create a service class: ng generate service services/auth

This create a AuthService in /services directory

Routing​

Angular features a built-in router for implementing navigation between pages. Here are the steps to set up the navigation routes:

  1. Add provideRouter in app.config.ts

    export const appConfig: ApplicationConfig = {
    providers: [provideRouter(routes)]
    };
  2. Setup a list of routes in app.routes.ts

    export const routes: Routes = [
    { path: '', component: MainPage },
    { path: 'login', component: LoginPage },
    { path: '**', component: NotFoundPage }, // all other routes
    ];
  3. Add RouterLink, RouterLinkActive, and RouterOutlet to your AppComponent's imports option

    @Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, RouterLink, RouterLinkActive],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
    })
    export class AppComponent {}
  4. Add the routes to your app-component.html. <router-outlet> tells Angular to render the selected route’s component view into the application.

    <nav>
    <ul>
    <li><a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home</a></li>
    <li><a routerLink="/login" routerLinkActive="active" ariaCurrentWhenActive="page">Login</a></li>
    </ul>
    </nav>

    <router-outlet></router-outlet>

For more advanced routing techniques in Angular, visit the official documentation.

Environment Configuration​

Angular has a built-in feature to customise configuration for different environments such as dev, staging, prod, etc. Follow the steps below.

Step 1:​

Run ng generate environments to generate default environment files. Angular will generate the following files:

  • environments/environment.ts - file as the default config
  • angular.json - where you define the environments

Step 2:​

Create a custom environment file, eg. environments/environment.staging.ts and copy the values from the default config file here.

Step 3:​

Run ng build --configuration staging and it will replace the environments/environment.ts with environments/environment.staging.ts

Concluding Thoughts​

Angular is a comprehensive web framework packed with built-in features that enable efficient and unified web application development. This guide merely scratches the surface of Angular's capabilities. For a deep dive into its more advanced features, check out the official documentation.

My .NET crash course

· 4 min read
Guster
Principal Engineer

image

ASP.NET is a popular MVC framework for building web applications with C#. It's similar to Spring Boot if you come from a Java background and other web frameworks like Ruby on Rails and Laravel. Personally, I think it's more comparable to Spring Boot. We'll discuss this more later.

Follow the official documentation for installation.

File Structure

When I start learning a new framework, I usually relate its features to ones I'm familiar with. For example:

  • ApiController - Define a REST Controller, like @RestController in Spring Boot
  • DbContext - Think of it like a JpaRepository factory in Spring Boot, or ActiveRecord in ROR
  • Program.cs - The main class where the app initialisation is done, similar to SpringBootApplication
  • .csproj - Where we define the configs, dependencies, like the maven pom.xml or build.gradle in Java
  • /Migrations - A folder containing the db migration files, similar to the migrations in ROR.

C#

As a newcomer to C#, I found it surprisingly straightforward to learn. This is partly due to its similarities with other languages I'm familiar with, such as Java, JS, Kotlin, Ruby, and Dart. Here are a few examples:

  • The public, protected, private keywords
  • The var and const variable assignment keywords
  • The getter and setter shorthands get; set; in Kotlin
  • The attribute [...], which is equivalent to the annotation @ in Java
  • The async and await keywords

Development with VSCode

To run .NET directly from VSCode, you need to install these 2 extensions first.

Once these extensions are installed, please F5 to launch and debug.

CLI Commands

One thing I like about Ruby on Rails is its powerful CLI. It allows you to scaffold, generate classes, run migrations, and more. Fortunately, .NET also has its own CLI, and it’s actually pretty good.

Here are some commonly used commands in .NET:

  • dotnet new - Create a new .NET project

    dotnet new webapi --use-controllers -o dotnet-todo-api
  • dotnet add package - Add a package dependency

    dotnet add package Microsoft.EntityFrameworkCore.InMemory

    # If you are just starting, install these
    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design 1 ↵ guster@Gusters-MacBook-Air
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools
    dotnet tool uninstall -g dotnet-aspnet-codegenerator
    dotnet tool install -g dotnet-aspnet-codegenerator
    dotnet tool update -g dotnet-aspnet-codegenerator

    # for postgresql
    Aspire.Npgsql.EntityFrameworkCore.PostgreSQL
  • dotnet tool - Install a CLI extension

    # install the Entity Framework CLI tool for database migration
    dotnet tool install --global dotnet-ef
  • dotnet ef migrations - Generate a migration file

    dotnet ef migrations add InitialCreate
  • dotnet ef database update - Apply the migrations to database

  • dotnet aspnet-codegenerator - Scaffolding such as controller

    dotnet aspnet-codegenerator controller -name TodoItemsController -async -api -m TodoItem -dc TodoContext -outDir Controllers
  • dotnet run watch - Run the project with hot reloading

How-to List

  • How to enable CORS?​

    If you are developing SPA with framework like React or Angular locally, you might hit CORS error when calling API to your local API server. To enable CORS, this is how you do it.

    How to

    In Program.cs, add the following codes.

    builder.Services.AddCors(options =>
    {
    options.AddDefaultPolicy(builder =>
    {
    builder.AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod();
    });
    });

    var app = builder.Build();
    // ...
    app.UseCors();
  • Add a singleton​

    In Program.cs, add the following changes, assuming you have created a service AuthService, then inject it in your class’s constructor as usual.

    builder.Services.AddSingleton<AuthService>()
  • Authorisation with JWT​

    Setup

    To begin with, add the following service in your Program.cs

    builder.Services
    .AddAuthorization()
    .AddAuthentication(options =>
    {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters = new TokenValidationParameters
    {
    ValidateAudience = false,
    ValidateActor = false,
    ValidateIssuer = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    LogValidationExceptions = true,
    ValidIssuer = "valid_issuer",
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
    };
    });

    ...

    var app = builder.Build();

    // IMPORTANT: the order matters!
    app.UseAuthentication();
    app.UseAuthorization();

    Helper class to generate a JWT token (AuthService)

    public class AuthService
    {
    public string GenerateJwtToken(User user)
    {
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("your_secret_key");
    var tokenDescriptor = new SecurityTokenDescriptor
    {
    Subject = new ClaimsIdentity(
    [
    new Claim("id", user.Id.ToString())
    ]),
    Issuer = "valid_issuer",
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
    }
    }

    Protect your API endpoints

    In your Controller, add this annotation [Authorize] to any endpoint method that required authorisation. Default is anonymous allowed.

How to configure Reverse Proxy on Windows IIS

· 3 min read
Guster
Principal Engineer

Photo by Brett Sayles from Pexels

Much like Nginx, IIS is a web server on Windows that allows you to configure to serve different kinds of purpose. From serving static files, to hosting a php application directly using, etc. However, IIS isn't as straight forward as Nginx when it comes to setting up a reverse proxy. This artcile will show you how to setup reverse proxy in a Windows IIS server.