OpenStreetMap API for JavaScript/TypeScript
The `osm-api` package provides a robust JavaScript/TypeScript wrapper for interacting with the OpenStreetMap API, designed for both Node.js (requiring Node.js >=18) and browser environments. Currently stable at version 4.0.0 (last published February 2026), the library facilitates common OSM operations such as fetching map features, managing changesets, user data, messaging, and notes. It automatically converts OSM's XML responses into JSON format, simplifying data handling for developers. A key differentiator is its use of OAuth 2 for authentication, enhancing security by avoiding the direct exposure of OAuth `client_secret`s. The library is lightweight (24 kB gzipped) and offers a simpler API and TypeScript support compared to older alternatives like `osm-request`. While a specific fixed release cadence is not explicitly stated, updates are released to address critical changes, such as the security patches to OSM's authentication flow, requiring timely library updates (e.g., v3.0.0 for a specific popup mode authentication fix).
Common errors
-
ReferenceError: OSM is not defined
cause Attempting to use `OSM` object in a browser environment without including the `<script>` tag, or trying to use CommonJS `require` in an ESM context without a proper bundler setup.fixFor browsers, ensure `<script src="https://unpkg.com/osm-api@latest"></script>` is included before your script. For modern Node.js/bundled environments, use `import * as OSM from 'osm-api';`. -
TypeError: (0 , osm_api_1.default) is not a function
cause Attempting to use `import OSM from 'osm-api';` when the library primarily exports a namespace (`* as OSM`) rather than a default export.fixChange your import statement to `import * as OSM from 'osm-api';` to correctly import the namespace. -
Error: "Authentication failed: popup mode requires library update and land.html modification."
cause Attempting to use the `popup` authentication mode with an outdated `osm-api` library version (prior to v3.0.0) or without updating the `land.html` snippet after recent OSM security changes.fixUpgrade `osm-api` to version 3.0.0 or newer via `npm install osm-api@latest` and ensure your `land.html` file includes the latest required code snippet for popup authentication. -
HTTP Error 401 Unauthorized
cause Attempting an authenticated API call without successfully logging in or with expired/invalid OAuth credentials (e.g., wrong `client_id`, `redirect_uri`, or scope).fixVerify your OAuth 2 `client_id`, `redirect_uri`, and requested `scope` are correct and that the user has successfully completed the authentication flow and granted necessary permissions. Ensure your tokens are fresh if managing them manually.
Warnings
- breaking Authentication using the `popup` mode broke due to security changes on OpenStreetMap's side (effective July 8, 2025).
- gotcha The library requires Node.js version 18 or higher for server-side usage.
- gotcha OpenStreetMap's editing API has strict usage policies; clients may be blocked if they affect service levels or cause data corruption. Automated edits require community consultation.
- gotcha Authentication via OAuth 2 requires careful handling of `client_id` and `redirect_uri`. Misconfiguration can lead to failed login attempts or security vulnerabilities.
- gotcha OSM API requests, especially for large areas or complex queries, can occasionally result in server-side timeouts (e.g., 50x errors) or rate limiting due to high load on the volunteer-maintained OSM infrastructure.
Install
-
npm install osm-api -
yarn add osm-api -
pnpm add osm-api
Imports
- OSM
import OSM from 'osm-api';
import * as OSM from 'osm-api';
- OSM
const OSM = require('osm-api'); - OSM (global)
import { getFeature } from 'osm-api';<script src="https://unpkg.com/osm-api@4"></script>
Quickstart
import * as OSM from 'osm-api';
async function runOsmApiExample() {
try {
// Public API call - no authentication required
const feature = await OSM.getFeature('way', 23906749);
console.log('Fetched feature:', feature);
// Authenticated API calls require login first.
// In a real application, replace these with your actual OAuth 2 client details
// and handle the authentication flow (e.g., popup or redirect).
// This is a placeholder for demonstration purposes.
const authConfig = {
client_id: process.env.OSM_CLIENT_ID ?? 'YOUR_CLIENT_ID',
redirect_uri: process.env.OSM_REDIRECT_URI ?? 'YOUR_REDIRECT_URI',
scope: 'write_changesets,write_notes',
};
// This would typically involve a browser redirect or popup.
// For a Node.js script, you'd likely manage tokens manually after an initial authorization step.
// const authenticatedOSM = await OSM.login(authConfig);
// console.log('Successfully attempted login (mock):', authenticatedOSM);
// Example of an authenticated call (requires actual login to work)
// Assuming an authenticated instance or global auth state after login
// For this example, we'll simulate the call, but it won't work without actual auth.
console.log('Attempting to create a changeset comment (requires authentication)...');
// const commentResult = await OSM.createChangesetComment(114733070, 'Thanks for your edit!');
// console.log('Changeset comment result:', commentResult);
} catch (error) {
console.error('An error occurred:', error.message);
if (error.response) {
console.error('OSM API Error details:', error.response.status, error.response.data);
}
}
}
runOsmApiExample();