Design the backend that charges the right sales tax or VAT at checkout: quotes from a tax provider cached per cart, the tax recorded exactly as charged when the order is paid, refunds that reverse it, and per-jurisdiction totals for registration thresholds, then build it in TypeScript with Encore.

Sales tax looks like a percentage on the cart until a customer two streets away sits in another tax district, a refund has to return the tax, and finance asks where you must register.
Rather than owning rate tables, call a tax API at the right moments and store exactly what it returned. This guide designs that backend, then builds it in TypeScript with Encore.
A US rate depends on state, county, city and special districts at the ship-to address, and on whether that state taxes the product at all: clothing, food and digital goods differ by state. VAT has its own reduced rates per country. Tax providers maintain that data and return the tax per line for an address and a product tax code, so the backend stores what they answer instead of owning rules that change monthly.
Stripe Tax, used in the code below, splits this into a calculation for the quote and a transaction for the commit. Other providers have the same two steps under different names, so the design carries over.
The cart asks for a quote whenever the items or the address change. Cache quotes by a hash of the cart and address, so a page refresh does not call the provider again, and drop them before the provider expires them.
When payment is captured, turn the quote into a committed transaction keyed by the order ID. That is the record you report and remit, so it must happen exactly once per order: check for an existing commit first and send an idempotency key with the request. Stripe's create_from_calculation accepts calculations for 90 days, which covers authorize-then-capture flows with a gap between them.
Store the per-line tax from the commit and never recompute it. Rates change, and an order from March has to show March's tax in every report and every refund.
A refund reverses tax against the committed transaction, fully or for specific lines, as Stripe's reversal API does. Partial refunds are where hand-rolled math drifts: refund the tax the provider attributes to the returned lines, not the order's average rate times the refund amount.
Your duty to collect at all depends on where you have registered. In the US, South Dakota v. Wayfair let states require remote sellers to collect once sales pass a threshold, and the law in that case applied above $100,000 of sales or 200 separate transactions a year. Each state now sets its own threshold and measurement period. In the EU, distance sales of goods to consumers above an EU-wide EUR 10,000 threshold are taxed in the customer's country, typically reported through the One Stop Shop.
The backend's part is data: sales and order counts per state or country for the current period, from committed transactions, so finance sees a state approaching a threshold before you pass it. Subtract refunds if the jurisdiction measures net sales.
Decide the outage policy before launch: blocking checkout is safe for tax and costs sales during an outage. Charging an estimate keeps checkout open, but you then owe the difference on any order you under-collected. Many stores block for new addresses and estimate from a recent quote for the same postal code and tax code, and log every estimated order for review.
Encore is a backend framework with built-in infrastructure, and the tax service declares its database and the provider key as a secret in TypeScript next to the endpoints, and Encore provisions the database in your AWS or GCP account. Bookshop.org moved from a Rails monolith to Go microservices with Encore, with a 95% reduction in DevOps workload.

Run in your terminal to get started locally.
Test-mode keys go to development, local and preview environments and the live key only to production. Secret values are stored by Encore, not in the repository.
-- tax/migrations/1_create_tables.up.sql
CREATE TABLE quotes (
cart_hash TEXT PRIMARY KEY, -- sha256 of the normalized cart and address
calculation_id TEXT NOT NULL, -- the provider's calculation
tax_cents BIGINT NOT NULL,
lines JSONB NOT NULL, -- per-line tax as the provider returned it
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE committed (
order_id TEXT PRIMARY KEY,
transaction_id TEXT NOT NULL,
country TEXT NOT NULL,
region TEXT NOT NULL, -- US state or EU country
sales_cents BIGINT NOT NULL,
tax_cents BIGINT NOT NULL,
lines JSONB NOT NULL,
committed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// tax/tax.ts
import { createHash } from "node:crypto";
import { api, APIError } from "encore.dev/api";
import { secret } from "encore.dev/config";
import { SQLDatabase } from "encore.dev/storage/sqldb";
const db = new SQLDatabase("tax", { migrations: "./migrations" });
const stripeKey = secret("StripeSecretKey");
interface Line {
sku: string;
quantity: number;
amountCents: number; // line total before tax
taxCode: string; // product tax code, e.g. txcd_99999999 for general goods
}
interface Address {
line1: string;
city: string;
state: string;
postalCode: string;
country: string;
}
interface QuoteRequest {
currency: string;
shipTo: Address;
lines: Line[];
shippingCents: number;
}
interface LineTax {
sku: string;
taxCents: number;
}
interface QuoteResponse {
quoteId: string; // the provider calculation, passed to commit at order time
taxCents: number;
lines: LineTax[];
}
// The cart page asks for a quote on every change. Identical carts reuse the
// stored calculation instead of calling the provider again.
export const quote = api(
{ expose: true, method: "POST", path: "/tax/quote" },
async (req: QuoteRequest): Promise<QuoteResponse> => {
const hash = createHash("sha256").update(JSON.stringify(req)).digest("hex"); // same cart, same hash
const cached = await db.queryRow<{ calculation_id: string; tax_cents: number; lines: LineTax[] }>`
SELECT calculation_id, tax_cents, lines FROM quotes
WHERE cart_hash = ${hash} AND expires_at > now() + interval '1 day'`;
if (cached) {
return { quoteId: cached.calculation_id, taxCents: Number(cached.tax_cents), lines: cached.lines };
}
const form = new URLSearchParams({
currency: req.currency,
"customer_details[address_source]": "shipping",
"customer_details[address][line1]": req.shipTo.line1,
"customer_details[address][city]": req.shipTo.city,
"customer_details[address][state]": req.shipTo.state,
"customer_details[address][postal_code]": req.shipTo.postalCode,
"customer_details[address][country]": req.shipTo.country,
"shipping_cost[amount]": String(req.shippingCents),
"expand[0]": "line_items",
});
req.lines.forEach((l, i) => {
form.set(`line_items[${i}][amount]`, String(l.amountCents));
form.set(`line_items[${i}][quantity]`, String(l.quantity));
form.set(`line_items[${i}][reference]`, l.sku);
form.set(`line_items[${i}][tax_code]`, l.taxCode);
});
const calc = await stripe("/v1/tax/calculations", form);
const lines: LineTax[] = calc.line_items.data.map((li: { reference: string; amount_tax: number }) => ({
sku: li.reference,
taxCents: li.amount_tax,
}));
const taxCents = calc.tax_amount_exclusive + calc.tax_amount_inclusive;
await db.exec`
INSERT INTO quotes (cart_hash, calculation_id, tax_cents, lines, expires_at)
VALUES (${hash}, ${calc.id}, ${taxCents}, ${JSON.stringify(lines)}::jsonb, to_timestamp(${calc.expires_at}))
ON CONFLICT (cart_hash) DO UPDATE SET calculation_id = EXCLUDED.calculation_id,
tax_cents = EXCLUDED.tax_cents, lines = EXCLUDED.lines, expires_at = EXCLUDED.expires_at`;
return { quoteId: calc.id, taxCents, lines };
},
);
interface CommitRequest {
orderId: string;
quoteId: string;
}
// Called once payment is captured. Records the tax that was charged, exactly
// as quoted, so later rate changes never rewrite a past order.
export const commit = api(
{ expose: false, method: "POST", path: "/tax/commit" },
async ({ orderId, quoteId }: CommitRequest): Promise<{ transactionId: string }> => {
const done = await db.queryRow<{ transaction_id: string }>`
SELECT transaction_id FROM committed WHERE order_id = ${orderId}`;
if (done) return { transactionId: done.transaction_id };
const tx = await stripe(
"/v1/tax/transactions/create_from_calculation",
new URLSearchParams({ calculation: quoteId, reference: orderId, "expand[0]": "line_items" }),
`tax-commit-${orderId}`,
);
const addr = tx.customer_details.address;
const sales = tx.line_items.data.reduce((s: number, li: { amount: number }) => s + li.amount, 0);
const tax = tx.line_items.data.reduce((s: number, li: { amount_tax: number }) => s + li.amount_tax, 0);
await db.exec`
INSERT INTO committed (order_id, transaction_id, country, region, sales_cents, tax_cents, lines)
VALUES (${orderId}, ${tx.id}, ${addr.country}, ${addr.state ?? addr.country}, ${sales}, ${tax},
${JSON.stringify(tx.line_items.data)}::jsonb)
ON CONFLICT (order_id) DO NOTHING`;
return { transactionId: tx.id };
},
);
interface RegionTotal {
country: string;
region: string;
salesCents: number;
orders: number;
}
// Sales and order counts per state or country this calendar year, for
// comparing against each jurisdiction's registration thresholds.
export const exposure = api(
{ expose: false, method: "GET", path: "/tax/exposure" },
async (): Promise<{ regions: RegionTotal[] }> => {
const rows = await db.queryAll<RegionTotal>`
SELECT country, region, SUM(sales_cents)::bigint AS "salesCents", COUNT(*)::int AS orders
FROM committed
WHERE committed_at >= date_trunc('year', now())
GROUP BY country, region
ORDER BY SUM(sales_cents) DESC`;
return { regions: rows.map((r) => ({ ...r, salesCents: Number(r.salesCents) })) };
},
);
async function stripe(path: string, body: URLSearchParams, idempotencyKey?: string): Promise<any> {
const headers: Record<string, string> = {
Authorization: `Bearer ${stripeKey()}`,
"Content-Type": "application/x-www-form-urlencoded",
};
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const res = await fetch(`https://api.stripe.com${path}`, { method: "POST", headers, body });
const json = await res.json();
if (!res.ok) {
if (res.status === 400) throw APIError.invalidArgument(json.error?.message ?? "tax calculation failed");
throw APIError.unavailable("tax provider unavailable");
}
return json;
}
With an encore.service.ts file in tax/, encore run starts a local Postgres, applies the migration and serves the endpoints against the provider's test mode. Your order service calls commit when payment is captured, and exposure feeds a monthly report. On deploy, the database runs on RDS or Cloud SQL, and Encore provisions an IAM role for the service.
A coding agent adding refunds writes the reversal endpoint and its table change in TypeScript and runs it locally in the same change, with the provider key already available in every environment and no database to provision first.
The hand-built version has the same endpoints on ECS or Cloud Run, a managed Postgres database, the provider key in a secrets manager with IAM for the service to read it, and networking between the service and the database, defined in Terraform. The tax logic is identical. The extra work is the infrastructure around it and keeping it consistent across environments.
Use a tax API for the rates and rules. US sales tax depends on the exact ship-to address and on product taxability that differs by state, and VAT rates and rules change across EU countries. The backend's job is to call the API at the right moments, store what it returned and keep the totals you need for registration decisions.
Quote at checkout and commit when payment is captured. A quote is an estimate the customer sees, while a committed transaction is what you report and remit, so committing before payment would report tax on orders that never complete.
After the 2018 Supreme Court decision in South Dakota v. Wayfair, US states can require remote sellers to collect sales tax once their sales into the state pass a threshold. The South Dakota law in that case applied above $100,000 of sales or 200 transactions a year, and each state sets its own rules.
With Encore, declare the database and the tax provider key as a secret in TypeScript next to the quote, commit and exposure endpoints. Deploys provision the database in your own AWS or GCP account, and the secret values are stored by Encore rather than in the repository.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.