Country States Database

0.0.10 · active · verified Wed Apr 22

The `country-states` package provides a lightweight, focused database containing country and state/subdivision data, primarily adhering to the ISO 3166-2 standard. It offers a programmatic way to access geographical subdivisions for various countries. As of version 0.0.10, it is in an early but functional state, likely receiving updates as data changes or expands, rather than on a strict release cadence. Its key differentiator lies in its simplicity and direct access to structured country-state information without complex APIs or extensive feature sets, making it suitable for applications requiring basic geographical data lookups where detailed geographic features are not needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize country data using `compile` and then retrieve specific state information using `states`, highlighting the importance of pre-compilation for desired country codes.

import { compile, states } from 'country-states';

// It's crucial to call `compile` with the country codes you intend to use
// before attempting to retrieve states. This initializes the data for those countries.
// ISO 3166-1 alpha-2 codes are used here.
compile(['US', 'CA', 'DE', 'AU']);

console.log('States for United States (US):');
const usStates = states('US');
if (usStates && usStates.length > 0) {
  console.log(`  Total US states/territories: ${usStates.length}`);
  console.log('  First 3 US states:', usStates.slice(0, 3).map(s => s.name).join(', '));
} else {
  console.log('  No data found for US.');
}

console.log('\nStates for Germany (DE):');
const deStates = states('DE');
if (deStates && deStates.length > 0) {
  console.log(`  Total German states/territories: ${deStates.length}`);
  console.log('  First 3 German states:', deStates.slice(0, 3).map(s => s.name).join(', '));
} else {
  console.log('  No data found for DE. Did you include it in compile()?');
}

// Attempting to access a country not compiled will return undefined or an empty array.
console.log('\nStates for France (FR) without prior compilation:');
const frStates = states('FR');
if (frStates && frStates.length > 0) {
  console.log(`  Total FR states/territories: ${frStates.length}`);
} else {
  console.log('  No data found for FR, as it was not included in compile().');
}

// You can inspect the structure of a state object
if (usStates && usStates.length > 0) {
  console.log('\nExample state object (from US):', usStates[0]);
}

view raw JSON →