> ## Documentation Index
> Fetch the complete documentation index at: https://docs.countrystatecity.in/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI

> Official @countrystatecity/cli — search, explore, and generate code from the terminal, with typo-tolerant fuzzy search and live plan data

Official CLI for the Country State City API — search, explore, and generate code from geographic data, right from your terminal.

[Get a free API key](https://app.countrystatecity.in?source=sdk_docs\&campaign=sdk_api_migration\&package=cli) to start, then [compare plans](https://countrystatecity.in/pricing?source=sdk_docs\&campaign=sdk_api_migration\&package=cli) when you need more data, higher limits, fuzzy search, or autocomplete.

<Note>
  Like the [TypeScript SDK](/api/sdks/typescript) — which the CLI is built on internally — this calls the **live API**, not a bundled snapshot. It needs an API key and is subject to your plan's usage quotas. For offline/bundled data with no API key, see [npm Packages](/api/sdks/npm).
</Note>

## Installation

```bash theme={null}
npm install -g @countrystatecity/cli
```

## Quick Start

```bash theme={null}
# 1. Get your free API key at https://app.countrystatecity.in
csc auth login

# 2. Search countries
csc search countries

# 3. Get country details
csc get country IN
```

## Global Flags

These flags work on every command:

| Flag          | Short | Description                                     |
| ------------- | ----- | ----------------------------------------------- |
| `--json`      |       | Output raw JSON instead of formatted tables     |
| `--quiet`     | `-q`  | Suppress all decorative output (spinners, tips) |
| `--no-footer` |       | Hide the API usage footer after each command    |

## Authentication

```bash theme={null}
csc auth login                # Interactive login with API key
csc auth login --key <KEY>    # Login with key directly
csc auth status               # Check current auth status
csc auth logout               # Remove stored API key
```

## Search

```bash theme={null}
csc search countries
csc search countries --filter "united"
csc search states --country IN
csc search cities --country IN --state MH
csc search regions   # Requires Supporter+ plan
csc search india     # Global search — matches country names
```

### Fuzzy, typo-tolerant search

<Note>**Requires Professional+ plan.**</Note>

Works two ways:

**Global**, across a chosen entity type:

```bash theme={null}
csc search "Mumbay" --type city --country IN --fuzzy
```

`--type` defaults to `city` if omitted. `--country` scopes results and isn't used with `--type country`.

**Per-entity**, reusing `--filter`'s value as the fuzzy query:

```bash theme={null}
csc search countries --filter "Indea" --fuzzy
csc search states --country IN --filter "Maharastra" --fuzzy
csc search cities --country IN --filter "Mumbay" --fuzzy
```

`--fuzzy` requires `--filter` on these subcommands — the CLI exits with an error if you pass `--fuzzy` without it. On `cities`, `--state` is ignored when `--fuzzy` is set, since fuzzy search only scopes by country.

Fuzzy results replace the usual per-entity table with a shared one:

| Column   | Meaning                                                               |
| -------- | --------------------------------------------------------------------- |
| Type     | `country`, `state`, or `city`                                         |
| Name     | Matched name                                                          |
| Location | State + country for cities, country for states, blank for countries   |
| ID       | Record ID                                                             |
| Score    | Match confidence — the API's `match_score`, shown to 2 decimal places |

### `--fields` and `--sort`

<Note>**Requires Supporter+ plan.**</Note>

Available on `search countries`/`states`/`cities` — passed straight through to the API instead of the CLI always fetching full objects:

```bash theme={null}
csc search cities --country IN --fields name,population --sort population:desc
csc search countries --fields name,iso2 --sort name:asc
```

<Note>
  When `--fields` narrows the response, output falls back to a generic table showing whatever columns actually came back — the CLI's usual hardcoded columns (ISO2, Capital, Phone, and so on) may not all be present anymore.
</Note>

## Get Details

```bash theme={null}
csc get country IN
csc get country US --json
csc get country           # Interactive — prompts to pick a country (TTY only)

csc get state IN MH
csc get state              # Interactive — prompts for country then state (TTY only)
```

## Usage & Billing

```bash theme={null}
csc usage
csc usage --json          # Returns { plan, price, daily, monthly }

csc upgrade
csc upgrade --json        # Returns { plans, currentPlan }
```

<Note>
  `csc upgrade` fetches live plan and pricing data from the API on every run, so what you see always matches the current [pricing page](https://countrystatecity.in/pricing?source=sdk_docs\&campaign=sdk_api_migration\&package=cli) — it isn't a table baked into the CLI's own code that can drift out of date.
</Note>

## Plan-Gated Features

Hitting a command your plan doesn't include shows the specific plan you need and a direct upgrade link, not just a generic message:

```
Access denied — this endpoint requires a higher plan.
Requires: Professional plan or higher.
Run `csc upgrade` to view available plans: https://app.countrystatecity.in/pricing
```

## Code Generation

<Note>**Requires Supporter+ plan.**</Note>

Generate ready-to-use components and seed files from live API data:

```bash theme={null}
csc generate dropdown --entity countries --format react
csc generate dropdown -e states -f react --country IN
csc generate seed --entity countries --format prisma
csc generate seed -e states -f prisma --country IN
```

## Live Location Components

These commands create live components that call the [Autocomplete API](/api/endpoints/get-search-autocomplete) as the user types. Unlike `dropdown` and `seed`, they do not download data when you generate the files, so the generator works offline.

<Note>
  The generated component needs a **Professional or Business** API plan when it runs. [Get an API key](https://app.countrystatecity.in?source=cli_docs\&campaign=location_components\&package=cli) or [compare plans](https://countrystatecity.in/pricing?source=cli_docs\&campaign=location_components\&package=cli).
</Note>

```bash theme={null}
# Type-ahead search field
csc generate autocomplete --target nextjs         # server API route + client component (recommended)
csc generate autocomplete --target react-browser  # calls the API directly from the browser

# Cascading country → state → city picker
csc generate location-picker --target nextjs
csc generate location-picker --target react-browser
```

`--target` is required: `nextjs` or `react-browser`. `--output <dir>` defaults to the current directory. Both generators always produce TypeScript (`.tsx`) — there's no `--typescript`/`--no-typescript` toggle like `dropdown` has.

### Choosing a target

<Tabs>
  <Tab title="nextjs (recommended)">
    Generates a server Route Handler (`app/api/csc-search/route.ts`) that holds `CSC_API_KEY` server-side and proxies to the Autocomplete API — the key never reaches the browser. `autocomplete` and `location-picker` share this same route file when both are generated with `nextjs`.
  </Tab>

  <Tab title="react-browser">
    No server — the generated component calls the API directly from the browser via the SDK, so the key ships in your JavaScript bundle.

    <Warning>
      Before using a `react-browser`-generated component, create an API key in your CSC dashboard **restricted to your site's origin(s)**. Never use an unrestricted/server key here — it would be visible in the browser and every outgoing request. The CLI prints this warning before writing any files, and it's repeated in both the generated component's header comment and the generated README, so it survives past the initial run.
    </Warning>
  </Tab>
</Tabs>

### What gets generated

Every run also writes an `.env.example` and a short README:

| Command                                  | Files                                                                                                              |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `autocomplete --target nextjs`           | `app/api/csc-search/route.ts`, `components/LocationAutocomplete.tsx`, `.env.example`, `CSC-AUTOCOMPLETE-README.md` |
| `autocomplete --target react-browser`    | `components/LocationAutocomplete.tsx`, `.env.example`, `CSC-AUTOCOMPLETE-README.md`                                |
| `location-picker --target nextjs`        | `app/api/csc-search/route.ts`, `components/LocationPicker.tsx`, `.env.example`, `CSC-LOCATION-PICKER-README.md`    |
| `location-picker --target react-browser` | `components/LocationPicker.tsx`, `.env.example`, `CSC-LOCATION-PICKER-README.md`                                   |

`.env.example` uses a placeholder, never a real key — `CSC_API_KEY=YOUR_API_KEY_HERE` for `nextjs`, `VITE_CSC_API_KEY=YOUR_API_KEY_HERE` for `react-browser`.

For safety, the command stops before writing anything if one of these files already exists. It never replaces your existing files.

### Behavior

Both components share the same search-field logic:

* Debounced input (\~250ms), 2-character minimum before searching
* Cancels the previous in-flight request when new input arrives, so a slow response never overwrites a newer one
* Five distinct states — `loading`, `empty`, `plan-restricted`, `rate-limited`, `network-error` — each with its own message, not one generic error
* Full keyboard support: `ArrowUp`/`ArrowDown` to move, `Enter` to select the highlighted result, `Escape` or `Tab` to close
* ARIA combobox pattern (`role="combobox"`, `aria-expanded`, `aria-controls`, `aria-autocomplete`, `aria-activedescendant`) for screen readers

<Note>
  Selections carry stable identifiers (`id`, `iso2`, `country_code`, `state_code`, depending on entity) alongside the display `label`. Use the identifiers for anything programmatic — storing a selection, filtering a follow-up request, and so on. `label` is for display only.
</Note>

`location-picker` cascades three fields — country, then state, then city. The state field is disabled until a country is picked; the city field is disabled until a state is picked. Selecting a country clears both state and city; selecting a state clears only city:

```typescript theme={null}
export interface LocationPickerValue {
  country: IAutocompleteResult | null;
  state: IAutocompleteResult | null;
  city: IAutocompleteResult | null;
}
```

`autocomplete` reports its selection via `onSelect?: (result: IAutocompleteResult) => void`. `location-picker` reports the whole cascade via `onChange?: (value: LocationPickerValue) => void`, called after every level changes.

## Interactive Explorer

```bash theme={null}
csc explore
```

Pick a country, then a state, then an action — view cities, view full details, or get the equivalent `csc generate` command to copy-paste.

<Note>Requires an interactive terminal (TTY). Use `csc search` for scripts.</Note>

## Export

```bash theme={null}
csc export           # Opens the online bulk export tool in your browser
csc export --json    # Returns the export URL as JSON, useful for scripts
```

## Source

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dr5hn/countrystatecity-npm/tree/main/packages/cli">
    View the CLI source, open issues, or contribute.
  </Card>

  <Card title="npm Package" icon="npm" href="https://www.npmjs.com/package/@countrystatecity/cli">
    View published versions and changelog.
  </Card>
</CardGroup>
