---
title: Using namespaces
description: Create scoped Drift views without allocating separate stores or manually prefixing keys.
url: https://pr-15-c0fdf0ef9f59.thally.app/guides/using-namespaces
---

# Using namespaces

Create scoped Drift views without allocating separate stores or manually prefixing keys.

Namespaces isolate key views inside one Drift store. They share capacity,
expiry defaults, event listeners, LRU order, and persistence.

## Create scoped views

```typescript
import { createStore } from "driftkv";

const store = createStore<object>();
const users = store.namespace("users");
const sessions = store.namespace("sessions");

users.set("alice", { id: 1, name: "Alice" });
sessions.set("alice", { token: "xyz" });

users.get("alice"); // { id: 1, name: "Alice" }
sessions.get("alice"); // { token: "xyz" }
users.keys(); // ["alice"]
store.keys(); // ["users:alice", "sessions:alice"]
```

A view exposes the complete `DriftStore` interface. Its `keys()`, `values()`,
`entries()`, `size()`, `isEmpty()`, `clear()`, and `sweep()` methods operate
only on keys with that prefix. Reported keys are relative to the view.

## Nest namespaces

```typescript
const tenant = store.namespace("tenants").namespace("acme");
tenant.set("config", { plan: "pro" });

tenant.keys(); // ["config"]
store.keys(); // ["users:alice", "sessions:alice", "tenants:acme:config"]
```

The exported `NAMESPACE_DELIMITER` is `":"`. A colon inside a namespace name
is equivalent to nesting, so `namespace("tenants:acme")` addresses the same
prefix as the nested expression above.

## Account for shared behavior

- A `set()` in one namespace can evict the least recently used entry in
  another when the shared `maxEntries` limit is reached.
- Event listeners are store-wide and receive the full prefixed key.
- `flush()` on any view writes every entry in the backing store.
- A root `set("users:alice", value)` is visible as `get("alice")` from the
  `users` view. Namespaces are a key-prefix convention, not access control.

Use separate stores when you need separate limits, persistence files, event
streams, or security boundaries.