npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@josh-dovey/postcodes

v0.1.0

Published

Typed JavaScript/TypeScript client for the GB Postcodes API — lookup, autocomplete, boundaries, distance, radius, reverse geocode, and ONSPD geography.

Readme

@josh-dovey/postcodes

A typed JavaScript/TypeScript client for the GB Postcodes API. Lookup, autocomplete, boundaries, distance, radius search, reverse geocoding, and full ONSPD geography — in one small, dependency-free client.

npm version npm downloads license: MIT bundle size

  • 🪶 Zero dependencies — nothing riding along in your node_modules
  • 📦 ESM + CommonJS, fully typed, tree-shakeable
  • 🌍 Runs anywhere — Node 18+, Bun, Deno, Cloudflare/Vercel edge workers, and the browser
  • 🔁 Built-in retries with backoff, jitter, and Retry-After handling
  • 🧭 Everything geospatial — GeoJSON boundaries, radius search, reverse geocoding, distance matrices
  • 🎯 Payload control — ask for exactly the fields you need, nothing more
npm install @josh-dovey/postcodes
import { PostcodesClient } from '@josh-dovey/postcodes';

const postcodes = new PostcodesClient({
    apiKey: process.env.POSTCODES_API_KEY,
});

const sw1a = await postcodes.get('SW1A 1AA');

sw1a?.center; // { type: 'Point', coordinates: [-0.1416, 51.5011] }
sw1a?.geom; // GeoJSON Polygon boundary, ready for MapLibre or Leaflet
sw1a?.local_authority_name; // 'Westminster'

Contents

Configuration

| Option | Default | Notes | | --------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | | apiKey | process.env.POSTCODES_API_KEY | Sent as X-API-Key. Not needed for areas() or health(). | | baseUrl | process.env.POSTCODES_API_URL, else https://postcodes-api.co.uk | Origin with or without the /api suffix; both work. | | timeout | 10000 | Per-request, in milliseconds. 0 disables it. | | retries | 2 | Applies to timeouts, network errors, 429s, and 5xxs. | | retryDelay | 500 | Base backoff in milliseconds, doubled each attempt, with jitter. | | maxRetryDelay | 30000 | Ceiling for one wait, including a Retry-After the server sends. | | headers | {} | Extra headers on every request. | | fetch | global fetch | Swap in your own for tests or a custom agent. | | onRateLimit | — | Called with the rate-limit headers on every response that has them. |

Every method also takes signal, timeout, and retries to override the client defaults for one call.

Methods

Lookup

await postcodes.get('SW1A 1AA'); // Postcode | null
await postcodes.autocomplete('SW1A'); // Postcode[] — for typeaheads
await postcodes.lookup('SW1A 1AA'); // the raw response: Postcode | Postcode[]
await postcodes.validate('sw1a1aa'); // { valid: true, normalized: 'SW1A 1AA', type: 'unit' }
await postcodes.geography('SW1A 1AA'); // ONSPD admin, census, NHS, and police geography

lookup() mirrors the API exactly: an exact unit comes back as one object, anything broader (area, district, sector, partial) comes back as the postcodes inside it. get() and autocomplete() normalize that to a single shape so you do not have to branch.

Batch

const results = await postcodes.search(['SW1A 1AA', 'M1 1AE', 'ZZ1 1ZZ']);

results['SW1A1AA']?.center; // keyed by normalized code — uppercase, no spaces
results['ZZ11ZZ']; // null when a code does not resolve

The API accepts 100 codes per request; pass more and the client splits the list across sequential requests and merges the result. Use normalizePostcode() if you need to build those keys yourself.

Distance and proximity

await postcodes.distance('SW1A 1AA', 'M1 1AE', { unit: 'miles' }); // { distance: 162.9, unit: 'miles' }
await postcodes.nearest('SW1A 1AA', { n: 5 }); // { unit, results: [{ name, distance, ... }] }
await postcodes.radius('SW1A 1AA', 2, { unit: 'km', limit: 200 }); // everything within 2km
await postcodes.matrix(['SW1A 1AA', 'M1 1AE', 'EH1 1YZ']); // pairwise distances, 2–20 codes

Distances are straight-line, centroid to centroid, in km (default) or miles.

Geospatial

// Which postcode is this coordinate in?
await postcodes.reverse(51.5011, -0.1416); // unit by default
await postcodes.reverse(51.5011, -0.1416, { type: 'district' });

// Which postcodes fall inside a drawn delivery zone?
await postcodes.within({
    type: 'Polygon',
    coordinates: [
        [
            [-0.2, 51.4],
            [-0.2, 51.6],
            [0.1, 51.6],
            [-0.2, 51.4],
        ],
    ],
});

// Postcode-area boundaries for a map viewport (no API key needed)
await postcodes.areas({
    bbox: [-0.2, 51.4, 0.1, 51.6],
    fields: ['name', 'geom'],
});

Population

const reach = await postcodes.radiusPopulation('SW1A 1AA', 5, { unit: 'km' });

reach.census_residents; // Census 2021 residents across the unit postcodes in range
reach.estimated_residents; // ONS mid-year estimate
reach.unit_count; // how many unit postcodes were summed

Health

const health = await postcodes.health(); // { status: 'operational', checks: {...}, timestamp }

Trimming the payload

Boundary geometry is by far the largest part of a response. Ask for only what you use:

await postcodes.get('SW1A 1AA', { fields: ['name', 'center'] });
await postcodes.radius('SW1A 1AA', 5, {
    fields: ['name', 'center', 'census_residents'],
});

fields is fully typed — POSTCODE_FIELDS exports the whole list. name always comes back, whether you ask for it or not. When you do want geometry but not at full fidelity, detail simplifies it server-side:

await postcodes.get('SW1A 1AA', { detail: 'low' }); // 'low' | 'medium' | 'high' (default)

Errors

Every failure throws a subclass of PostcodesError, carrying the API's own message plus status, body, and retryAfter.

import {
    NotFoundError,
    RateLimitError,
    PostcodesError,
} from '@josh-dovey/postcodes';

try {
    await postcodes.get('ZZ1 1ZZ');
} catch (error) {
    if (error instanceof NotFoundError) return null;
    if (error instanceof RateLimitError)
        console.log(`retry in ${error.retryAfter}s`);
    if (error instanceof PostcodesError)
        console.error(error.status, error.message);
    throw error;
}

| Error | When | | --------------------- | ----------------------------------------------------------- | | BadRequestError | 400, plus client-side checks (empty batch, matrix bounds) | | AuthenticationError | 401 — missing, invalid, or expired key | | ForbiddenError | 403 — IP restriction, missing scope, demo-key limits | | NotFoundError | 404 — postcode or coordinate did not resolve | | RateLimitError | 429 — per-second, per-minute, or plan quota | | ServerError | 5xx | | TimeoutError | the request timeout or your signal fired | | NetworkError | no response at all — DNS, TLS, offline |

Timeouts, network errors, 5xxs, and rate limits are retried automatically (retries, default 2), honouring Retry-After. An exhausted plan quota is not retried — it will not clear in a few hundred milliseconds.

Rate limits

const postcodes = new PostcodesClient({
    apiKey: process.env.POSTCODES_API_KEY,
    onRateLimit: ({ remaining, quotaWarning }) => {
        if (quotaWarning) console.warn(quotaWarning); // fires from 80% of plan quota
    },
});

postcodes.rateLimit; // { limit, remaining, keyExpiresIn, quotaWarning } from the last response

Cancellation

const controller = new AbortController();
setTimeout(() => controller.abort(), 250);

await postcodes.autocomplete(input, { signal: controller.signal });

Development

npm install
npm test        # node:test against the TypeScript sources
npm run typecheck
npm run build   # dist/esm + dist/cjs + .d.ts

Requests go to https://postcodes-api.co.uk unless baseUrl or POSTCODES_API_URL says otherwise — point either at https://postcodes.test to work against a local instance.

License

MIT © Joshua Dovey