Back-end14 min read
Migrating a Node.js API to .NET without stopping the system
How to migrate an Express API to ASP.NET Core 11 gradually: a shared database, a YARP gateway and contract tests that caught 8 differences in the first version.

Rewriting an entire API and switching everything over one weekend is the riskiest way to migrate. While the new version isn't ready, the old one keeps getting fixes and features, and on switch day you discover everything that behaved differently all at once.
This post shows the safer path: both APIs running at the same time, a gateway in front sending each route to one of them, and a set of contract tests proving the client can't tell the difference. The example is an orders API in Express migrating to ASP.NET Core 11.
An honest note: everything here was actually run. The full code is in the node-to-dotnet-migration repository, with CI on GitHub running the tests against all three pieces. And the first .NET version, a direct translation of the Node code, failed 8 of the 10 tests. Those differences are the most useful part of the post.
TL;DR#
- Don't rewrite everything at once. Put a gateway in front and migrate route by route, with an easy way back.
- Before writing C#, write contract tests in plain HTTP that run against either API.
- The "obvious" translation changes the contract: the enum becomes
Pending, the date changes format, the validation error changes shape, the 404 loses its body. - A shared database requires both sides to write the same format. Otherwise one service stops finding what the other wrote.
- YARP handles the gateway with a configuration file.
- Reads first, writes later, and Node leaves last.
Before you start: the map#
Coming from Node, you'll find almost everything under another name:
| In Node | In .NET |
|---|---|
package.json, npm | .csproj, NuGet |
| Express, Fastify | ASP.NET Core (Minimal APIs or controllers) |
app.use(...) | app.Use(...), middleware |
| Zod, Joi | DataAnnotations with AddValidation(), or FluentValidation |
| manual injection or NestJS | built-in dependency injection (builder.Services) |
| Prisma, TypeORM, Knex | Entity Framework Core, Dapper |
process.env | IConfiguration (environment variables, appsettings.json) |
| Jest + supertest | xUnit + WebApplicationFactory |
nodemon, tsx watch | dotnet watch |
async/await with Promise | async/await with Task |
Two pieces of good news: System.Text.Json in Minimal APIs already serializes in camelCase, just like JavaScript, and attribute-based validation became built into Minimal APIs starting with .NET 10.
About versions: .NET 11 came out on November 10, 2026 and is STS. .NET 10 is LTS. Since Microsoft extended STS support to 24 months, both end together, in November 2028. For a migration starting now, either one works.
The strategy: strangle, don't rewrite#
The name comes from the strangler fig, which grows around a tree until it takes its place. Martin Fowler named the pattern after seeing these figs in a rainforest in Australia: the new system grows next to the old one, takes over one part at a time, and the old one disappears when there's nothing left for it to do.
The repository has four pieces:
node-api/: the current API, in Express 5, Zod andnode:sqlite.dotnet-api/: the same API in ASP.NET Core 11 with EF Core 11.gateway/: a reverse proxy with YARP.contract/: the HTTP tests that run against any of the three.
Step 1: the contract becomes a test#
The API's contract is everything the client sees: routes, status codes, field names, date format, error bodies. Before writing a line of C#, all of that needs to be written as a test, and the test can't know which language the API was built in. That's why it speaks only HTTP, with Node's own fetch and node:test, against a URL that comes from an environment variable:
// The same HTTP tests run against the Node API, the .NET API and the gateway.
// If they pass on all three, clients can't tell which one answered.
import { test } from 'node:test'
import assert from 'node:assert/strict'
const BASE_URL = process.env.BASE_URL ?? 'http://localhost:3000'
async function call(method, path, body) {
const response = await fetch(`${BASE_URL}${path}`, {
method,
headers: body ? { 'content-type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
})
const text = await response.text()
return { status: response.status, headers: response.headers, body: text ? JSON.parse(text) : null }
}
test('POST /orders creates an order with the agreed shape', async () => {
const { status, headers, body } = await call('POST', '/orders', {
customer: 'Ana',
totalCents: 4990,
})
assert.equal(status, 201)
assert.equal(headers.get('location'), `/orders/${body.id}`)
assert.deepEqual(Object.keys(body).sort(), ['createdAt', 'customer', 'id', 'status', 'totalCents'])
assert.equal(body.customer, 'Ana')
assert.equal(body.totalCents, 4990)
assert.equal(body.status, 'pending')
assert.match(body.createdAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
})
test('POST /orders trims the customer name', async () => {
const { body } = await call('POST', '/orders', { customer: ' Bia ', totalCents: 100 })
assert.equal(body.customer, 'Bia')
})
test('POST /orders rejects invalid input with the same error format', async () => {
const { status, body } = await call('POST', '/orders', { customer: '', totalCents: -5 })
assert.equal(status, 400)
assert.equal(body.error, 'validation_failed')
assert.deepEqual(body.details.map((d) => d.path).sort(), ['customer', 'totalCents'])
})There are ten tests in total: create, fetch, filter, update, and the error cases for each. Notice they check details nobody remembers to document: the exact set of keys in the object, the Location header, the date with three millisecond digits and a Z at the end, the field name in the error. That's exactly where a migration breaks clients.
Step 2: the API that already exists#
The Node API is small and direct. It's the reference: the tests passed against it first.
import express, { type Response } from 'express'
import { z } from 'zod'
import { OrdersRepository, STATUSES } from './orders-repository.ts'
const createOrderSchema = z.object({
customer: z.string().trim().min(1).max(100),
totalCents: z.number().int().positive(),
})
const updateStatusSchema = z.object({
status: z.enum(STATUSES),
})
const listQuerySchema = z.object({
status: z.enum(STATUSES).optional(),
})
function validationFailed(res: Response, error: z.ZodError) {
return res.status(400).json({
error: 'validation_failed',
details: error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message,
})),
})
}
function notFound(res: Response) {
return res.status(404).json({ error: 'not_found' })
}
export function createApp(orders: OrdersRepository) {
const app = express()
app.use(express.json())
The repository converts the database's snake_case to the API's camelCase in a single place, and the table looks like this:
import { DatabaseSync } from 'node:sqlite'
export function openDatabase(path = process.env.DATABASE_PATH ?? 'orders.db') {
const db = new DatabaseSync(path)
db.exec(`
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer TEXT NOT NULL,
total_cents INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL
)
`)
return db
}A detail of current Node: it runs TypeScript directly, with no build, by stripping the types. But it only accepts syntax that can be erased. constructor(private readonly db: DatabaseSync) doesn't work, because it generates code. The erasableSyntaxOnly option in tsconfig flags this in the editor.
Step 3: the first .NET version#
This is the translation anyone would write looking at the Node code: an enum for the status, DateTimeOffset for the date, validation attributes, and the EF Core entity returned directly.
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
namespace Orders.Api.Orders;
public record CreateOrderRequest(
[property: Required, StringLength(100, MinimumLength = 1)] string Customer,
[property: Range(1, int.MaxValue)] int TotalCents);
public record UpdateStatusRequest(OrderStatus Status);
public static class OrdersEndpoints
{
public static void MapOrders(this IEndpointRouteBuilder app)
{
var orders = app.MapGroup("/orders");
orders.MapGet("/", async (OrderStatus? status, OrdersDbContext db) =>
{
var query = db.Orders.AsQueryable();
if (status is not null) query = query.Where(o => o.Status == status);
return await query.OrderBy(o => o.Id).ToListAsync();
});
orders.MapGet("/{id:long}", async (long id, OrdersDbContext db) =>
await db.Orders.FindAsync(id) is { } order
? Results.Ok(order)
: Results.NotFound());
orders.MapPost("/", async (CreateOrderRequest request, OrdersDbContext db) =>Two good things already show up. The database is injected as a handler parameter, with no decorator or container to configure. And EF Core points at the table Node created, with each column's name, instead of creating a new schema:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Map to the table the Node API already created. No new schema.
modelBuilder.Entity<Order>(order =>
{
order.ToTable("orders");
order.Property(o => o.Id).HasColumnName("id");
order.Property(o => o.Customer).HasColumnName("customer");
order.Property(o => o.TotalCents).HasColumnName("total_cents");
order.Property(o => o.Status).HasColumnName("status").HasConversion<string>();
order.Property(o => o.CreatedAt).HasColumnName("created_at");
});
}It compiled on the first try. The contract tests against it, in node --test TAP format:
not ok 1 - POST /orders creates an order with the agreed shape
not ok 2 - POST /orders trims the customer name
not ok 3 - POST /orders rejects invalid input with the same error format
ok 4 - GET /orders/:id returns the order
not ok 5 - GET /orders/:id returns 404 for an unknown id
not ok 6 - GET /orders filters by status
not ok 7 - GET /orders rejects an unknown status filter
not ok 8 - PATCH /orders/:id/status updates the status
not ok 9 - PATCH /orders/:id/status rejects an unknown status
ok 10 - PATCH /orders/:id/status returns 404 for an unknown id
# pass 2
# fail 8What the tests caught#
| Difference | Node | First .NET version |
|---|---|---|
| Status in JSON and in the database | pending | Pending |
created_at written to the database | 2026-11-22T22:07:25.286Z | 2026-11-22 22:07:44.907267+00:00 |
createdAt in JSON | ...25.286Z | ...25.286+00:00 |
| Validation error body | { error, details[] } | ProblemDetails with errors{} |
| 404 body | { "error": "not_found" } | empty |
Unknown ?status= | 400 with details | 400 with an empty body |
| Customer name | trimmed | with the spaces |
The last five break the client. The first two are worse, because they silently corrupt data.
The status. HasConversion<string>() writes the enum name, Pending. The Node API filters with WHERE status = 'pending', and in SQLite that comparison is case sensitive. Result: every order created by .NET disappears from Node's filtered list.
The date. EF Core writes DateTimeOffset to SQLite as text, with a space instead of the T and the full offset. The column is text, so ORDER BY created_at compares character by character. Since a space comes before T, a .NET order created at 11 p.m. shows up before a Node order created at 8 a.m. the same day.
Neither one throws an error. Both pass any test that only looks at the .NET side. They only show up when both services use the same database, which is why the repository has a test that reads the raw row, the way Node sees it.
Step 4: speaking the contract's language#
The whole fix is in a single commit, and the diff is the best summary of the post.
Dates in JavaScript's format. A helper with the same format as toISOString(), used both to write to the database and to respond:
using System.Globalization;
namespace Orders.Api.Orders;
// Same format as JavaScript's Date.prototype.toISOString(): 2026-11-22T14:03:07.123Z
public static class IsoDate
{
private const string Pattern = "yyyy-MM-dd'T'HH:mm:ss.fff'Z'";
public static string Format(DateTimeOffset value) =>
value.UtcDateTime.ToString(Pattern, CultureInfo.InvariantCulture);
public static DateTimeOffset Parse(string value) =>
DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
}In the DbContext, the column now uses that format:
order.Property(o => o.CreatedAt)
.HasColumnName("created_at")
.HasConversion(value => IsoDate.Format(value), text => IsoDate.Parse(text));A DTO separate from the entity. Returning the EF Core entity directly seems practical, but then any change to the database model changes the JSON. A response record makes the contract explicit:
namespace Orders.Api.Orders;
public static class OrderStatus
{
public const string Pending = "pending";
public const string Paid = "paid";
public const string Shipped = "shipped";
public const string Cancelled = "cancelled";
}
public class Order
{
public long Id { get; set; }
public required string Customer { get; set; }
public int TotalCents { get; set; }
public string Status { get; set; } = OrderStatus.Pending;
public DateTimeOffset CreatedAt { get; set; }
}
// What the API returns. Kept apart from the entity so the JSON contract
// doesn't change by accident when the database model does.
public record OrderResponse(long Id, string Customer, int TotalCents, string Status, string CreatedAt)
{
public static OrderResponse From(Order order) => new(
order.Id,
order.Customer,
order.TotalCents,
order.Status,
IsoDate.Format(order.CreatedAt));
}The status became a string with constants. You could keep the enum with converters for the database and the JSON, but an unknown value in the body becomes a deserialization error, which skips validation and doesn't come out in the expected format. With string and [AllowedValues], an invalid value goes through validation like any other field:
public record CreateOrderRequest(
[property: Required, StringLength(100)] string Customer,
[property: Range(1, int.MaxValue)] int TotalCents);
public record UpdateStatusRequest(
[property: Required, AllowedValues(
OrderStatus.Pending, OrderStatus.Paid, OrderStatus.Shipped, OrderStatus.Cancelled)]
string Status);The old error format, in a single place. ASP.NET Core responds to validation failures with ProblemDetails (RFC 9457), a good standard for a new API. But this API's clients expect { error, details }. Instead of validating by hand in each route, an IProblemDetailsWriter translates the result of the built-in validation:
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Orders.Api;
// The error format the Node API already returns. Clients depend on it,
// so the .NET side speaks it too.
public record ErrorDetail(string Path, string Message);
public record ErrorBody(
string Error,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
IReadOnlyList<ErrorDetail>? Details = null);
public static class ApiErrors
{
public static NotFound<ErrorBody> NotFound() => TypedResults.NotFound(new ErrorBody("not_found"));
}
// ASP.NET Core reports validation failures as ProblemDetails.
// This writer translates them to the old format in a single place.
public class LegacyValidationErrorWriter : IProblemDetailsWriter
{
public bool CanWrite(ProblemDetailsContext context) =>
context.ProblemDetails is HttpValidationProblemDetails;
public ValueTask WriteAsync(ProblemDetailsContext context)
{
var problem = (HttpValidationProblemDetails)context.ProblemDetails;
var details = problem.Errors
.SelectMany(field => field.Value.Select(message =>
new ErrorDetail(JsonNamingPolicy.CamelCase.ConvertName(field.Key), message)))
.ToList();
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
return new ValueTask(context.HttpContext.Response.WriteAsJsonAsync(
new ErrorBody("validation_failed", details)));
}
}It's registered before AddProblemDetails(), so it's consulted before the default writer:
using Microsoft.EntityFrameworkCore;
using Orders.Api;
using Orders.Api.Orders;
var builder = WebApplication.CreateBuilder(args);
var databasePath = builder.Configuration["DATABASE_PATH"] ?? "orders.db";
builder.Services.AddDbContext<OrdersDbContext>(options =>
options.UseSqlite($"Data Source={databasePath}"));
// Registered before AddProblemDetails so it runs before the default writer.
builder.Services.AddSingleton<IProblemDetailsWriter, LegacyValidationErrorWriter>();
builder.Services.AddProblemDetails();
builder.Services.AddValidation();
builder.Services.AddOpenApi();
var app = builder.Build();One difference was left on purpose: the messages. Zod says one thing, .NET says another. The tests check the field, not the text. If a client shows the message to the user, it's part of the contract too and needs to be in the test.
With that, all ten tests pass against .NET, on the same database file Node is using.
Step 5: the gateway with YARP#
YARP is Microsoft's reverse proxy, an ASP.NET Core library. The gateway's Program.cs has four useful lines:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();And the whole migration lives in a configuration file. Today, order reads go to .NET and everything else stays on Node:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ReverseProxy": {
"Routes": {
"orders-reads": {
"ClusterId": "dotnet",
"Order": 1,
"Match": { "Path": "/orders/{**rest}", "Methods": ["GET"] }
},
"everything-else": {
"ClusterId": "node",
"Order": 100,
"Match": { "Path": "{**catch-all}" }
}
},
"Clusters": {
"node": {
"Destinations": { "primary": { "Address": "http://localhost:3000" } }
},
"dotnet": {
"Destinations": { "primary": { "Address": "http://localhost:5080" } }
}
}
}
}The more specific route has a lower Order and wins. To migrate the next route, you add an entry. To roll back, you delete it. No client changes its URL.
Both APIs send an x-served-by header, which shows who answered:
GET /orders -> x-served-by: dotnet
GET /orders?status=paid -> x-served-by: dotnet
GET /orders/1 -> x-served-by: dotnet
POST /orders -> x-served-by: node
PATCH /orders/1/status -> x-served-by: nodeAnd the same ten tests, now against the gateway, pass. That proves the most important part: an order created by Node is read by .NET in the same format, and a status changed by Node shows up correctly in .NET's filter.
The scripts/contract-all.sh script starts all three services on a temporary database and runs the tests three times. The repository's CI does that on Node 24 and Node 26.
Tests on the .NET side#
The equivalent of supertest is WebApplicationFactory: the whole application runs in memory, with no port. The test most worth having is the one that reads the raw database, because it catches the difference that only shows up with two services:
[Fact]
public async Task Database_gets_the_same_values_the_node_side_writes()
{
var created = await _client.PostAsJsonAsync("/orders", new { customer = "Bia", totalCents = 100 },
TestContext.Current.CancellationToken);
var order = await created.Content.ReadFromJsonAsync<OrderResponse>(TestContext.Current.CancellationToken);
await _client.PatchAsJsonAsync($"/orders/{order!.Id}/status", new { status = "paid" },
TestContext.Current.CancellationToken);
// Read the raw row, the way the Node API sees it.
await using var connection = new SqliteConnection($"Data Source={_databasePath}");
await connection.OpenAsync(TestContext.Current.CancellationToken);
var command = connection.CreateCommand();
command.CommandText = "SELECT status, created_at FROM orders WHERE id = $id";
command.Parameters.AddWithValue("$id", order.Id);
await using var reader = await command.ExecuteReaderAsync(TestContext.Current.CancellationToken);
await reader.ReadAsync(TestContext.Current.CancellationToken);
Assert.Equal("paid", reader.GetString(0));
Assert.Equal(order.CreatedAt, reader.GetString(1));
}A version stumble: with xUnit v3 and the .NET 10 SDK onward, dotnet test complains that "Testing with VSTest target is no longer supported". The fix is to declare the new runner in global.json:
{
"sdk": {
"version": "11.0.100",
"rollForward": "latestFeature"
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}The migration order#
- Contract tests against the current API, until they cover what clients actually use.
- Gateway in front, sending everything to Node. Nothing changes for the client, but the piece is already in place.
- Reads first. Getting a read wrong doesn't corrupt data, and rolling back is editing one line.
- Writes later, one route at a time, with the raw database test passing.
- Turn off Node when the gateway no longer sends anything to it.
While both coexist, only one side owns the schema. Here it's Node, which creates the table, and EF Core only maps it. When Node leaves, EF Core takes over, by creating an initial migration from the existing database.
Two things aren't in the repository but matter for a real system. The first is shadow traffic: the gateway sends the request to both sides, responds with the old one and logs the differences. The second is per-route metrics, with errors and response times, to decide with numbers whether a migrated route can stay.
Checklist#
- Contract tests in plain HTTP, running against the old API, the new one and the gateway.
- The same format written to the database by both sides: dates, enums, casing.
- A response DTO separate from the ORM entity.
- The old error format preserved, translated in a single place.
- Error messages in the test, if the client shows them to the user.
- A single schema owner while both coexist.
- A gateway with a one-line rollback, and reads migrated before writes.
References#
Comments
Sign in with your GitHub account to comment.
Read next

Back-end13 min read
App built with AI: what to check before you ship

Back-end18 min read
What is RAG? Indexing, hybrid search and a real case

Back-end12 min read
What is MCP (Model Context Protocol)? A practical guide