@xenterprises/fastify-xgeocode
v1.3.0
Published
Fastify plugin for Geocodio API integration with address geocoding and reverse geocoding.
Downloads
15
Readme
@xenterprises/fastify-xgeocode
Fastify 5 plugin for the Geocodio API — geocode US addresses and ZIP codes, reverse-geocode coordinates, validate addresses, and calculate distances. For Fastify apps that need location data with a single decorator and zero boilerplate.
Install
npm install @xenterprises/fastify-xgeocode fastify@5Minimal example
import Fastify from "fastify";
import xGeocode from "@xenterprises/fastify-xgeocode";
const fastify = Fastify();
await fastify.register(xGeocode, {
apiKey: process.env.GEOCODIO_API_KEY, // the consumer owns env access
});
fastify.get("/location/:zip", async (request) => {
return fastify.xGeocode.getLatLongByZip(request.params.zip);
});
await fastify.listen({ port: 3000 });Options
All configuration arrives via app.register(xGeocode, options). The plugin never reads process.env — pass values in explicitly.
| Name | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| apiKey | string | — | Yes | Geocodio API key from geocod.io. Must be a non-empty string (empty/whitespace-only values throw at registration) |
| active | boolean | true | No | Set to false to skip registration entirely (no decorator added, apiKey not required) |
| fields | string | "cd,stateleg" | No | Comma-separated Geocodio fields to include (e.g. "timezone,census,cd"). Pass "" for none. See Geocodio fields docs |
Invalid options throw at registration time, e.g.:
xgeocode: missing required option `apiKey` (string), e.g. `app.register(xGeocode, { apiKey: 'your-geocodio-api-key' })`Decorators
The plugin adds one decorator: fastify.xGeocode, with six methods. No request-scoped decorators.
getLatLongByZip(zipCode): Promise<Object>
Geocode a US ZIP code (5-digit or ZIP+4). Throws on invalid input, API errors, or empty results.
const result = await fastify.xGeocode.getLatLongByZip("10001");
// { zip, lat, lng, formatted_address, city, county, state, country, addressComponents }getLatLongByAddress(address): Promise<Object>
Geocode a street address (minimum 3 characters).
const result = await fastify.xGeocode.getLatLongByAddress("1600 Pennsylvania Ave NW, Washington DC");
// { lat, lng, formatted_address, city, county, state, country, zip, addressComponents }getReverseGeocode(lat, lng): Promise<Object>
Get an address from coordinates. Accepts numbers or numeric strings; latitude must be in [-90, 90], longitude in [-180, 180].
const result = await fastify.xGeocode.getReverseGeocode(40.7128, -74.006);
// { lat, lng, formatted_address, city, county, state, country, zip, addressComponents }getDistance(lat1, lng1, lat2, lng2): Object
Distance between two points via the Haversine formula. Synchronous — no API call.
const distance = fastify.xGeocode.getDistance(40.7128, -74.006, 34.0522, -118.2437);
// { kilometers: 3944.42, miles: 2451.21, meters: 3944422 }batchGeocode(locations): Promise<Array>
Geocode up to 100 addresses or ZIP codes in parallel. Per-item failures are returned inline as { original, error, success: false } instead of throwing.
const results = await fastify.xGeocode.batchGeocode([
"10001",
"1600 Pennsylvania Ave NW, Washington DC",
"invalid address",
]);validateAddress(address): Promise<Object>
Validate an address and get its standardized form. Does not throw on unrecognized addresses or API errors — returns { valid: false, input, error } instead.
const result = await fastify.xGeocode.validateAddress("123 Main St");
// { valid: true, input, formatted, confidence, lat, lng, ... }Routes
None. The plugin only decorates the Fastify instance.
Error behavior
- Registration fails fast with descriptive errors naming the plugin, the option, and an example (see Options above).
- Runtime methods throw real
Errorobjects prefixed with[xGeocode]:- Invalid input:
Invalid input - zipCode must be a non-empty string,Invalid zip code format - must be 5 digits or 9 digits (ZIP+4),Invalid address - minimum 3 characters required,Invalid latitude/longitude ...,Invalid coordinates - latitude and longitude must be numbers - API failures:
Geocoding API returned {status}/Reverse geocoding API returned {status} - Empty results:
No results found - Batch misuse:
locations must be an array,locations array cannot be empty,batch size cannot exceed 100 locations
- Invalid input:
validateAddressis the exception: it resolves{ valid: false, error }for API errors and unrecognized addresses, and only throws on invalid input.
Requirements
- Node.js >= 20
- Fastify ^5.0.0 (peer dependency)
- A Geocodio API key for the geocoding methods (
getDistanceworks offline)
License
Proprietary — All Rights Reserved X Enterprises. See LICENSE.
