# Libraries

> Serve the files of geolith datasets from your own server: the Rust crate geolith-dataset (axum) and the npm package @geolith/dataset (Hono, Workers).

::info
**Status: live on the Scale plan.** The hosted Datasets API answers from api.geolith.app with a key. The libraries on this page serve the same kind of files from your own server, with no key and no plan.
::

geolith Data is a library as well as a hosted API. The same file server comes as a Rust crate and as an npm package. You point it at a store that holds the tree `geolith dataset upload` writes (rainfall, NDVI or your own dataset), mount it in your own server, and it answers with the live build, its numbers, its map layer and the boundary tiles. The two packages give the same routes, the same headers and status codes and the same bytes: a cross-language test serves one fixture through both and compares every response.

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

Both 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.

They read what [`geolith-dataset-builder`](https://crates.io/crates/geolith-dataset-builder) writes: `<dataset>/<cc>/current.json`, the build folders and the boundary releases. Build a dataset with [`geolith dataset`](/datasets/build-your-own), or use a folder you already have. The key prefix `datasets/` is the builder's default; change it with `prefix` in either library. Map tiles are read with the [tile server library](/tiles/self-hosting/edge-server).

## Routes

| Route                                                                          | Answer                                                         |
| ------------------------------------------------------------------------------ | -------------------------------------------------------------- |
| `/catalog`                                                                     | every dataset and country with a live build                    |
| `/{dataset}/{cc}/current`                                                      | the live build, its period and links                           |
| `/{dataset}/{cc}/current/{index.json,series.json,numbers.csv,numbers.parquet}` | the live build's file, with `Range` and `ETag`                 |
| `/{dataset}/{cc}/current/areas/{area}.json`                                    | one area                                                       |
| `/{dataset}/{cc}/{build}/{z}/{x}/{y}.png`                                      | a raster tile (latest period)                                  |
| `/{dataset}/{cc}/{build}/{period}/{z}/{x}/{y}.png`                             | a raster tile of a past period                                 |
| `/{dataset}/{cc}/{build}/tilejson.json`                                        | TileJSON with the legend                                       |
| `/boundaries/{cc}/{release}/{z}/{x}/{y}.mvt`                                   | a boundary vector tile (gzip passes through; 406 without gzip) |
| `/files/{path}`                                                                | any published file byte for byte: `Range`, `ETag`, 304, 416    |
| `/health`                                                                      | `{"ok":true}`                                                  |

- The pointer `current.json` is trusted for 60 seconds. A tile of a build the held pointer does not name reads it again (at most once per 10 seconds), so a new build is served as soon as it is published. When the store fails, the last good pointer is served.
- A well-formed build or release that is not the live one answers `204` with `Cache-Control: no-store`.
- A store failure is a `503` with `Retry-After: 1` and no key or message in the body.
- Set the public URL in production: links and TileJSON name their URLs from it.

The routes are not the hosted API's paths. The hosted API serves files under `/v1/datasets/files/`; see [Status](/datasets/status#live).

## Rust (axum)

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

```rust
use geolith_dataset::{Datasets, FsStore, router};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let datasets = Datasets::builder(FsStore::new("./published"))
        .base_path("/datasets")
        .public_url("http://127.0.0.1:4003")
        .build();
    let app = axum::Router::new().nest("/datasets", router(datasets));

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

`./published` holds `datasets/rainfall/in/current.json` and the build folders. Give the builder the same `base_path` you nest the router under. Run it and ask:

```bash
cargo run
curl 'http://127.0.0.1:4003/datasets/health'
curl 'http://127.0.0.1:4003/datasets/catalog'
curl 'http://127.0.0.1:4003/datasets/rainfall/in/current'
```

The first prints `{"ok":true}`. The `router` function is behind the default feature `axum`. For another framework, build a `Request` from yours (`Request::get(path)`), call `datasets.handle(&request).await` and map the `Response` back.

## TypeScript (Hono)

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

```ts
import { serve } from '@hono/node-server';
import { createHandler } from '@geolith/dataset';
import { FileStore } from '@geolith/dataset/stores/file';
import { Hono } from 'hono';

const handle = createHandler({
  store: new FileStore('./published'),
  basePath: '/datasets',
  publicUrl: 'http://127.0.0.1:4003',
});

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

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

Run it with Node 26 (`node server.ts`) and ask the same three questions. `createHandler` returns a web-standard `(Request) => Promise<Response>`, so it fits Bun, Deno and Nitro as well. The handler touches no platform API. Without a `cors` option no answer carries `Access-Control-Allow-Origin`.

### Cloudflare Workers

Keep the published tree in R2. An R2 binding is a store as it is:

```ts
import { createHandler } from '@geolith/dataset';
import { r2Store } from '@geolith/dataset/stores/r2';

export default {
  fetch: (request: Request, env: { BUCKET: R2Bucket }) =>
    createHandler({ store: r2Store(env.BUCKET) })(request),
};
```

Bind the bucket as `BUCKET` in your Wrangler configuration and deploy with `wrangler deploy`.

## Where the files live

Reads go through a store: whole objects and byte ranges by key, with the size and ETag, and nothing for a missing key.

| Where                                                    | Rust                                  | TypeScript                                       |
| -------------------------------------------------------- | ------------------------------------- | ------------------------------------------------ |
| A local folder                                           | `FsStore`                             | `@geolith/dataset/stores/file`                   |
| Objects in memory                                        | `MemoryStore`                         | `@geolith/dataset/stores/memory`                 |
| A Cloudflare R2 binding                                  |                                       | `@geolith/dataset/stores/r2`                     |
| S3, R2 (S3 API), Google Cloud Storage (HMAC keys), MinIO | `ObjectStoreAdapter` (feature `aws`)  | `@geolith/dataset/stores/s3` (needs `aws4fetch`) |
| Any server that honours `Range`                          | `ObjectStoreAdapter` (feature `http`) | `@geolith/dataset/stores/fetch`                  |

In Rust, `ObjectStoreAdapter` wraps any `object_store::ObjectStore`; the features `gcp` and `azure` add Google Cloud Storage and Azure Blob. Your own store implements two async methods, `get` and `head`.

```rust
use geolith_dataset::ObjectStoreAdapter;
use object_store::aws::AmazonS3Builder;

// Cloudflare R2 through its S3 API.
let r2 = AmazonS3Builder::new()
    .with_bucket_name("my-bucket")
    .with_endpoint("https://<account>.r2.cloudflarestorage.com")
    .with_region("auto")
    .with_access_key_id(key_id)
    .with_secret_access_key(secret)
    .build()?;
let store = ObjectStoreAdapter::new(r2, "");
```

## Typed reads

Both libraries also read the files without HTTP:

```ts
import { createDatasets } from '@geolith/dataset';

const datasets = createDatasets({ store });
const pointer = await datasets.current('rainfall', 'in');
const index = await datasets.index('rainfall', 'in', pointer.build_id);
```

In Rust, `datasets.current("rainfall", "in")`, `index` and `layer` do the same. The fields a library reads are typed and every other field passes through, so a field the builder adds later never breaks a reader.

## What is not in the libraries

API keys, plans, metering and rate limits belong to the hosted API, not to the libraries: put them in front of the handler in your own server. `Policy::hosted()` (Rust) and `hostedPolicy` (TypeScript) reproduce the hosted file answers for a service that wants them.
