DEV Community

Geocoding
Geocoding

Posted on

Geocode addresses in Node.js with fetch (no SDK needed)

Disclosure: I operate Geocoding.info. The code below uses only built-in Node.js APIs and the public Geocoding.info endpoints.

Turning a typed address into latitude and longitude is one of those features that sounds trivial until you ship it: you need a key that stays secret, results that arrive as strings, empty matches, rate limits and batches that should not hammer an API. This post walks through a small, dependency-free setup in Node.js that handles all of that.

What you need

  • Node.js 20 or newer (for the built-in fetch and AbortSignal.timeout)
  • A free API key from Geocoding.info

Keep the key out of your code:

export GEOCODING_API_KEY="your-key-here"
Enter fullscreen mode Exit fullscreen mode

1. A reusable geocode() function

The /search endpoint takes an address in q and returns an array of matches, best first. Asking for limit=1 and addressdetails=1 keeps the response small and gives you a structured address.

// geocode.mjs
const API_URL = 'https://api.geocoding.info/search';

export async function geocode(address, { country } = {}) {
  const key = process.env.GEOCODING_API_KEY;
  if (!key) throw new Error('Set GEOCODING_API_KEY');

  const params = new URLSearchParams({
    q: address, format: 'json', limit: '1',
    addressdetails: '1', 'accept-language': 'en', key,
  });
  if (country) params.set('countrycodes', country); // e.g. 'pk' or 'gb,ie'

  const response = await fetch(`${API_URL}?${params}`, {
    signal: AbortSignal.timeout(20_000),
  });
  if (!response.ok) {
    const body = await response.json().catch(() => ({}));
    throw new Error(`Geocoding failed: HTTP ${response.status} ${body.error?.code ?? ''}`.trim());
  }

  const [best] = await response.json();
  if (!best) return null;               // no match: the API returns []
  return {
    lat: Number(best.lat),              // lat/lon arrive as strings
    lon: Number(best.lon),
    label: best.display_name,
    country: best.address?.country_code,
  };
}
Enter fullscreen mode Exit fullscreen mode

Two details that trip people up:

  1. Coordinates are strings. The JSON comes from Nominatim, which returns "31.5881260", not a number. Convert before you hand it to a map library.
  2. No match is not an error. You get HTTP 200 with an empty array, so check before reading the first item.

Try it:

import { geocode } from './geocode.mjs';
console.log(await geocode('Badshahi Mosque, Lahore', { country: 'pk' }));
// { lat: 31.588126, lon: 74.3093528, label: 'Badshahi Mosque, Fort Road, …, Pakistan', country: 'pk' }
Enter fullscreen mode Exit fullscreen mode

2. Keep the key on the server

If you call the API from browser JavaScript, anyone can copy your key from DevTools and spend your quota. Put a tiny endpoint in front of it instead:

// server.mjs
import express from 'express';
import { geocode } from './geocode.mjs';

const app = express();

app.get('/api/geocode', async (req, res) => {
  const address = String(req.query.q ?? '').trim();
  if (!address || address.length > 200) {
    return res.status(400).json({ error: 'Provide an address of up to 200 characters.' });
  }
  try {
    res.json((await geocode(address)) ?? { found: false });
  } catch {
    res.status(502).json({ error: 'Geocoding is temporarily unavailable.' });
  }
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Your front end calls /api/geocode?q=.... Add caching and your own per-user limits before exposing it publicly.

3. Geocoding a list without getting rate limited

Every plan has a per-second limit, plus daily and 30-day allowances shared across all your keys. For batches, go one request at a time and pause:

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function geocodeAll(addresses) {
  const results = [];
  for (const address of addresses) {
    try {
      results.push({ address, ...(await geocode(address)) });
    } catch (error) {
      results.push({ address, error: error.message });  // keep going
    }
    await sleep(1000);
  }
  return results;
}
Enter fullscreen mode Exit fullscreen mode

When something does go wrong, the error body tells you why: invalid_api_key (401), rate_limit_exceeded, daily_quota_exceeded or monthly_quota_exceeded (429), or a temporary 503/504. Retry 429s a couple of times with a growing delay, then give up and log it instead of looping forever.

Going further

Results come from OpenStreetMap data via Nominatim, so coverage varies by area; map data © OpenStreetMap contributors.

What are you geocoding in your Node app? Happy to answer questions in the comments.

Top comments (0)