# Libraries

> Run geolith Search inside your own server: the Rust crate geolith-search (axum) and the npm package @geolith/search (Hono, Nitro, Workers), over one .glx file.

geolith Search is a library first. The same geocoder, with the same answers, comes as a Rust crate and as an npm package. You mount it in your own server, give it a `.glx` file and read the answers. There is no key check, no rate limit and no metering in either: put those in front of it, in your own server.

| Language   | Package                                                            | Runs in                                          |
| ---------- | ------------------------------------------------------------------ | ------------------------------------------------ |
| Rust       | [`geolith-search`](https://crates.io/crates/geolith-search)        | axum, actix or any framework                     |
| TypeScript | [`@geolith/search`](https://www.npmjs.com/package/@geolith/search) | Node, Bun, Deno, Cloudflare Workers, Hono, Nitro |

Both packages are source-available under FSL-1.1-ALv2. Use, change and self-host them freely, including commercially; offering them as a competing hosted service is not allowed. Each release becomes Apache-2.0 two years after it is published.

You need one `.glx` file. Build it with the [geolith builder](/builder), or try the library with a small sample file from the [`.glx` specification](/glx/overview#sample-files).

## Rust (axum)

```bash
cargo add geolith-search axum anyhow
cargo add tokio --features rt-multi-thread,macros,net
```

```rust
use axum::Router;
use geolith_search::store::Store;
use geolith_search::{AppState, Settings, router};
use std::path::Path;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let store = Store::open(Path::new("places.glx"))?;
    let geocoder = router(AppState::new(store, Settings::default()));
    let app = Router::new().nest("/geocode", geocoder); // /geocode/v1/search?text=...

    let listener = tokio::net::TcpListener::bind("127.0.0.1:4000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}
```

Run it and ask:

```bash
cargo run
curl 'http://127.0.0.1:4000/geocode/v1/search?text=india%20gate&size=1'
```

The first feature has `"label": "India Gate, New Delhi, India"`. The router serves `/v1/search`, `/v1/autocomplete`, `/v1/search/structured`, `/v1/reverse`, `/v1/nearby`, `/v1/place`, `/health`, `/openapi.json` and `/docs`. See the [API reference](/search/api/search) for every parameter.

### Any other framework

`AppState::handle` takes a path and the raw query string and returns a status code and a JSON body, so any framework can serve it. Build with `default-features = false` to leave axum out.

```rust
let reply = state.handle("/v1/search", Some("text=eiffel%20tower")).await;
assert_eq!(reply.status, 200);
```

## TypeScript (Hono)

```bash
pnpm add @geolith/search hono @hono/node-server
```

```ts
import { serve } from '@hono/node-server';
import { createHandler } from '@geolith/search';
import { FileSource } from '@geolith/search/sources/file';
import { Hono } from 'hono';

const handle = createHandler({
  source: new FileSource('./places.glx'),
  cors: { origins: ['https://example.com'] },
});

const app = new Hono();
app.all('*', (c) => handle(c.req.raw));

serve({ fetch: app.fetch, port: 4000 });
```

Run it with Node 26 (`node server.ts`) and ask:

```bash
curl 'http://127.0.0.1:4000/v1/search?text=india%20gate&size=1'
```

`createHandler` returns a web-standard `(Request) => Promise<Response>`, so the same handler fits Bun (`Bun.serve({ fetch: handle })`) and Deno. The package is ESM only.

### Nitro

In `nitro.config.ts` set `serverDir: 'server'`, then add one catch-all route, `server/routes/[...path].ts`:

```ts
import { createHandler } from '@geolith/search';
import { FileSource } from '@geolith/search/sources/file';
import { defineHandler } from 'nitro/h3';

const handle = createHandler({
  source: new FileSource('./places.glx'),
  cors: { origins: ['https://example.com'] },
});

export default defineHandler((event) => handle(event.req));
```

Build with `nitro build` and start `.output/server/index.mjs`. `GET /health` answers `{"status":"ok","places":N}`.

### Cloudflare Workers

A Worker cannot read a file at run time. Keep the `.glx` file in R2 and pass the reader as a module:

```ts
import wasm from '@geolith/glx/glx-parser.wasm';
import { createHandler } from '@geolith/search';
import { R2Source } from '@geolith/search/sources/r2';

let handle: ReturnType<typeof createHandler> | undefined;

export default {
  fetch(request: Request, env: { FILES: R2Bucket }) {
    handle ??= createHandler({
      source: new R2Source(env.FILES, 'planet.glx'),
      wasm,
    });
    return handle(request);
  },
};
```

Bind the bucket as `FILES` in your Wrangler configuration. Build the handler once per isolate; it keeps the open file and a block cache.

## Where the file lives

A query reads many small byte ranges, so the file can stay in object storage. A source says where.

| Where                                                  | Rust                           | TypeScript                                       |
| ------------------------------------------------------ | ------------------------------ | ------------------------------------------------ |
| A local file                                           | `FileSource`                   | `@geolith/search/sources/file`                   |
| Bytes in memory                                        | `MemorySource`                 | a `Source` over a `Uint8Array`                   |
| Any server that answers `Range`                        | `HttpSource` (feature `http`)  | `@geolith/search/sources/fetch`                  |
| Cloudflare R2 binding                                  |                                | `@geolith/search/sources/r2`                     |
| S3, R2 S3 API, Google Cloud Storage (HMAC keys), MinIO | `HttpSource` with a signed URL | `@geolith/search/sources/s3` (needs `aws4fetch`) |

```rust
use geolith_search::source::HttpSource;
let store = Store::from_source(HttpSource::new("https://example.com/places.glx"))?;
```

The TypeScript handler reads the source through a block cache, on by default: aligned 256 KiB blocks, kept in memory up to 32 MiB. Set `cache: false` or change `blockSize` and `maxBytes` in `createHandler`.

## Categories, language and parity

`categories` and `lang` work the same way as on the [hosted API](/search/hosted/overview#categories-and-language). The two packages are tested against each other: one fixture file, a list of requests for every route and filter, and the status and JSON body must be equal. The two differ on three deliberate points: the `geocoding.engine` name and version, the `/openapi.json` `info.version`, and `/docs` (served by the Rust router only).

## Run the server binary

[Running](/search/self-hosting/running) describes the `geolith-search` command: a thin server over the same crate.
