USPS releases ZIP Code polygons: how to use them with Bun
If you've ever needed to know "which ZIP Code is this point on the map in", you know the official answer used to be: there isn't one. The US Postal Service (USPS) now publishes the official ZIP Code polygons on its PostalPro portal, the outline of each postal area (source). It sounds like niche news. But a lot of people handle shipping, taxes, routing and data analysis on top of a map that, until yesterday, was a very polite hack. In this post I explain what changed and show how to turn these ZIP Code polygons into a lookup API with Bun.
Why was there no official ZIP Code map?
Because a ZIP Code was never an area. It's a delivery route. The mail carrier walks through a sequence of addresses, and that set gets a code. There's no border drawn anywhere. Just a list of streets and PO boxes.
That's why, for years, the world used an approximation: the Census Bureau's ZCTAs (ZIP Code Tabulation Areas). The Census takes census blocks, checks which ZIP shows up most in each one and draws a polygon. It works reasonably well. But it has three problems that anyone who has worked with it knows:
- It isn't USPS data, so it doesn't match postal reality 100%.
- It's updated at the Census pace, not the pace of the routes.
- Many PO box ZIPs or single-building ZIPs simply don't show up.
The result: there are around 41,000 ZIP Codes in the US and an "almost right" map of them. "Almost right" is great for a dashboard chart. For calculating sales tax, it's a headache.
If you're from Brazil, think of the CEP. Same logic: it's a street code, not an area code. And the full Correios database, the DNE, is paid. Watching USPS publish official outlines brings a bit of healthy envy.
What USPS actually published
The package is called ZIP Code Boundaries (ZCB) and lives on PostalPro, the USPS portal for high-volume mailers. The idea is simple: one polygon per ZIP Code, generated from USPS's own delivery data.
Before plugging it into your system, check three things on the page that change everything:
- File format. Shapefile, GeoJSON, something else? That defines your pipeline.
- License and cost. "Official" doesn't mean "free for commercial use". Read it before shipping to production.
- Update frequency. Routes change. If the file is quarterly, your cache has to be too.
I won't make up details the page doesn't make clear. What matters is this: there's now a source that the data owner itself stands behind.
A ZIP Code was never a place. It was a path that finally got an outline.
How to query ZIP Code polygons with Bun
The classic use case is this: a latitude and longitude come in and you want to return the ZIP. You can do it with no database and no dependencies, just Bun. It works for a prototype, a data enrichment script or a small microservice.
If the file comes as a shapefile, convert it first. One GDAL line does it:
ogr2ogr -f GeoJSON zips.geojson zcb.shp -t_srs EPSG:4326
The -t_srs EPSG:4326 makes sure the coordinates are plain longitude and latitude. A lot of "the point landed in the ocean" bugs are a wrong projection, not wrong code.
Now the service. It loads the GeoJSON once, computes the bounding box of each polygon and answers over HTTP:
// zip-lookup.ts
type Ring = [number, number][];
type Feature = {
properties: Record<string, string>;
geometry: { type: "Polygon" | "MultiPolygon"; coordinates: any };
};
const geo = await Bun.file("zips.geojson").json();
const index = geo.features.map((f: Feature) => {
const polys: Ring[][] =
f.geometry.type === "Polygon" ? [f.geometry.coordinates] : f.geometry.coordinates;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const [x, y] of polys.flatMap((p) => p[0])) {
minX = Math.min(minX, x); maxX = Math.max(maxX, x);
minY = Math.min(minY, y); maxY = Math.max(maxY, y);
}
// adjust the field name to match the real file
return { zip: f.properties.ZIP ?? f.properties.zip, polys, box: [minX, minY, maxX, maxY] };
});
function inRing(x: number, y: number, ring: Ring) {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i], [xj, yj] = ring[j];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
// the first ring is the outline, the others are holes
const inPolygon = (x: number, y: number, p: Ring[]) =>
inRing(x, y, p[0]) && !p.slice(1).some((hole) => inRing(x, y, hole));
function lookup(lng: number, lat: number) {
for (const z of index) {
const [a, b, c, d] = z.box;
if (lng < a || lng > c || lat < b || lat > d) continue;
if (z.polys.some((p: Ring[]) => inPolygon(lng, lat, p))) return z.zip;
}
return null;
}
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const lat = Number(url.searchParams.get("lat"));
const lng = Number(url.searchParams.get("lng"));
if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
return Response.json({ error: "lat and lng are required" }, { status: 400 });
}
return Response.json({ zip: lookup(lng, lat) });
},
});
Run it with bun zip-lookup.ts and test:
curl "localhost:3000?lat=40.7484&lng=-73.9857"
Notice that GeoJSON uses the [longitude, latitude] order. Everyone gets this wrong at least once. I got it wrong twice.
Where Bun helps (and where it stops)
Bun shines in three spots in this flow:
Bun.file().json()reads and parses a large file with no ceremony. Nofs.readFileplusJSON.parseplus encoding handling.- TypeScript out of the box. No
tsc, nots-node, no config. You write the.tsand run it. Bun.servespins up HTTP in a few lines and handles plenty of requests for a service this size.
The bounding box filter is what makes this fast. Instead of testing the point against 41,000 polygons, you discard almost all of them with four comparisons and only run ray casting on the few candidates. For a script that enriches a spreadsheet of 100,000 addresses, that's more than enough.
Where it stops: memory and scale. A detailed national GeoJSON can be hundreds of megabytes. Loading all of it into the RAM of every serverless instance is asking to pay a lot and wait for cold starts. And the linear loop over the index starts to hurt if you get thousands of queries per second.
When to swap the script for PostGIS
Here's my strong opinion: serious geometry belongs in the database, not in your application code. If the project is going to production and the data changes from time to time, import the polygons into PostgreSQL with PostGIS and let the spatial index do the work:
SELECT zip
FROM zip_boundaries
WHERE ST_Contains(geom, ST_SetSRID(ST_MakePoint(-73.9857, 40.7484), 4326))
LIMIT 1;
With a GiST index on the geom column, this query answers in milliseconds, no matter how many ZIPs there are. Updating the data becomes a TRUNCATE plus an import, with no redeploy. And the Bun service still exists, just as a thin layer that receives the request and queries the database.
The in-memory script still has its place: tests, one-off jobs, a CLI that runs on your laptop. Just don't let it become the source of truth for tax billing.
What this changes if you don't work with the US
If your product doesn't ship anything to the US, the direct impact is small. The indirect impact is a different story. When an agency publishes official data, libraries, geocoders and address SaaS start using it. The "which region buys the most" numbers get more reliable. And it sets a precedent: postal data can, in fact, become open data (or at least accessible data).
In my view, this news is more about data than code. The code to query a polygon has been the same for decades. What was missing was a polygon you could trust. Now there is one. If you want to see how I usually build this kind of small service with Bun and Postgres, there are a few examples in my projects.
LinkedIn summary
The US Postal Service finally drew the map that never existed. A ZIP Code was never an area. It was always a delivery route. For years, everyone used a Census approximation that was "almost right". Now USPS publishes the official polygon for every ZIP. If you calculate shipping, taxes or routing, this is a game changer. I tried turning those polygons into a lookup API with Bun, no database and no dependencies. It works really well for a prototype. But my opinion stands: serious geometry belongs in PostGIS, not in your application code. In the end, this news is more about data than code. I wrote the full step by step on the blog. The link is in the comments. #Bun #TypeScript #PostGIS #OpenData #Geolocation