supermemory/apps/docs/integrations/memory-graph.mdx
Muskan jain dd5fff13e4
docs: longer meta descriptions on 31 docs pages (#1909)
Co-authored-by: Muskan <275333692+muskanai0409-cell@users.noreply.github.com>
2026-11-27 21:09:00 +05:30

445 lines
14 KiB
Text

---
title: 'Memory Graph'
sidebarTitle: "Memory Graph"
description: "A React component that draws your Supermemory documents, memories and their connections as an interactive graph, with install steps, props and examples."
icon: "/icons/hugeicons/hierarchy-square-01.svg"
---
Memory Graph is a React component that visualizes your Supermemory documents and memories as an interactive network. Documents appear as rectangular nodes, memories as hexagonal nodes, and connections between them show relationships and similarity.
<Card title="@supermemory/memory-graph on npm" icon="/icons/hugeicons/package.svg" href="https://www.npmjs.com/package/@supermemory/memory-graph">
Check out the NPM page for more details
</Card>
## Installation
```bash
npm install @supermemory/memory-graph
```
**Requirements:** React 18.0.0 or higher
## Quick start
Two pieces: a server route that reads the signed-in user's graph, and `<MemoryGraph endpoint>` in the browser.
### 1. Add a server route
`fetchMemoryGraph` from `@supermemory/memory-graph/server` calls `POST /ns/{namespace}/graph` with your API key, follows `nextCursor` to the last page and returns the documents `MemoryGraph` renders. It uses only the global `fetch`, so it runs on Node 18+, Bun, Deno, Cloudflare Workers and other edge runtimes.
<CodeGroup>
```typescript Next.js App Router
// app/api/memory-graph/route.ts
import { fetchMemoryGraph, MemoryGraphError } from '@supermemory/memory-graph/server';
import { auth } from '@/auth'; // your auth
export async function POST() {
const user = await auth();
if (!user) return new Response('Unauthorized', { status: 401 });
try {
return Response.json(
await fetchMemoryGraph({
apiKey: process.env.SUPERMEMORY_API_KEY!,
namespace: user.id,
}),
);
} catch (error) {
if (error instanceof MemoryGraphError) {
return Response.json({ error: error.message }, { status: error.status });
}
throw error;
}
}
```
```typescript Express
import { fetchMemoryGraph, MemoryGraphError } from '@supermemory/memory-graph/server';
app.post('/api/memory-graph', requireUser, async (req, res, next) => {
try {
res.json(
await fetchMemoryGraph({
apiKey: process.env.SUPERMEMORY_API_KEY!,
namespace: req.user.id,
}),
);
} catch (error) {
if (error instanceof MemoryGraphError) {
return res.status(error.status).json({ error: error.message });
}
next(error);
}
});
```
```typescript Hono
import { fetchMemoryGraph, MemoryGraphError } from '@supermemory/memory-graph/server';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
app.post('/api/memory-graph', requireUser, async (c) => {
try {
return c.json(
await fetchMemoryGraph({
apiKey: c.env.SUPERMEMORY_API_KEY,
namespace: c.get('user').id,
}),
);
} catch (error) {
if (error instanceof MemoryGraphError) {
return c.json({ error: error.message }, error.status as ContentfulStatusCode);
}
throw error;
}
});
```
</CodeGroup>
<Warning>
Keep the API key on the server. It can read and write every namespace in your organization, so a key shipped to the browser lets anyone read every user's memories. Your route checks who is signed in and only ever passes that user's namespace.
</Warning>
`fetchMemoryGraph` options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | - | Your Supermemory API key |
| `namespace` | `string` | - | The namespace to read, usually the signed-in user's ID. Up to 100 letters, digits, `_`, `:` or `-`, so map IDs such as `auth0\|123` or emails first |
| `baseUrl` | `string` | `https://api.supermemory.ai` | API origin |
| `limit` | `number` | `100` | Documents per page (at most 100). Up to 20 pages are read |
On a failed request it throws `MemoryGraphError`, whose `status` is the API's status code and whose `message` is the API's reason: `400` for an invalid namespace or `limit`, `401` for a bad key, `403` when the key cannot read the namespace, `429` when rate limited.
```typescript
import { fetchMemoryGraph, MemoryGraphError } from '@supermemory/memory-graph/server';
try {
return Response.json(await fetchMemoryGraph({ apiKey, namespace }));
} catch (error) {
if (error instanceof MemoryGraphError) {
return Response.json({ error: error.message }, { status: error.status });
}
throw error;
}
```
### 2. Render the graph
```tsx
'use client'; // For Next.js App Router
import { MemoryGraph } from '@supermemory/memory-graph';
export default function MemoryGraphPage() {
return (
<div style={{ height: '100vh' }}>
<MemoryGraph endpoint="/api/memory-graph" variant="console" />
</div>
);
}
```
`MemoryGraph` sends a `POST` to `endpoint` (cookies are sent to a same-origin route, so your session auth applies) and shows a loading indicator, then the graph. An empty namespace shows "No memories yet" (override it with `labels.emptyGraph` or `children`), and a failed request shows the error.
### Other backends
From Python, Go, Ruby or any other server, call the API directly and return the result from your route:
1. `POST https://api.supermemory.ai/ns/{namespace}/graph?limit=100` with `Authorization: Bearer $SUPERMEMORY_API_KEY` and the JSON body `{}`.
2. The response is `{ nodes, edges, nextCursor }`. While `nextCursor` is not `null`, repeat the call with `&cursor=<nextCursor>`.
3. Return `{ "nodes": [...], "edges": [...] }` with the nodes and edges of every page. `<MemoryGraph endpoint>` accepts this shape as well as the array `fetchMemoryGraph` returns.
```python Python
import os, requests
from urllib.parse import quote
def memory_graph(namespace: str) -> dict:
nodes, edges, cursor = [], [], None
while True:
params = {"limit": 100, **({"cursor": cursor} if cursor else {})}
page = requests.post(
f"https://api.supermemory.ai/ns/{quote(namespace, safe='')}/graph",
params=params,
headers={"Authorization": f"Bearer {os.environ['SUPERMEMORY_API_KEY']}"},
json={},
)
page.raise_for_status()
data = page.json()
nodes += data["nodes"]
edges += data["edges"]
cursor = data["nextCursor"]
if not cursor:
return {"nodes": nodes, "edges": edges}
```
## Optional rendering and document navigation
Existing icon-based document nodes and connection styling remain the defaults. Opt in to stacked squares and stronger semantic connections with `appearance`:
```tsx
<MemoryGraph
documents={documents}
appearance={{ documentNodes: 'stacked', connections: 'emphasized' }}
openDocumentOnEnter
onOpenDocument={openPersistedDocument}
/>
```
`documentNodes` accepts `'icons'` or `'stacked'`; `connections` accepts `'default'` or `'emphasized'`. Both fields are optional and also work on `GraphCanvas`. Stacks stay inside existing node bounds and simplify at low zoom. Use `colors.edgeDocument` to configure document-source ink; older custom `GraphCanvas` palettes without that field use `textSecondary` in emphasized mode.
`openDocumentOnEnter` is off by default. With an `onOpenDocument` callback, `MemoryGraph` exposes a focused Enter action for the selected persisted document or one confirmed memory source. Typing, modifier shortcuts, repeats, composition and keys outside the graph do not open documents. Your callback retains responsibility for routing and access control; consumers without a callback receive no new opening behavior.
---
## Variants
**Console Variant** - Full dashboard view: themed surface with a dot grid, nodes colored by theme:
```tsx
<MemoryGraph documents={documents} variant="console" />
```
**Consumer Variant** - Embedded widget view: transparent surface, nodes colored by cluster:
```tsx
<MemoryGraph documents={documents} variant="consumer" />
```
---
## Examples
### Paging in the browser
To load pages on demand instead of the whole graph in one request, return one raw page from your route (step 1 of [Other backends](#other-backends), forwarding `cursor`) and pass `documents` yourself, converting each page with `graphPageToDocuments`:
```tsx
'use client';
import { MemoryGraph, graphPageToDocuments } from '@supermemory/memory-graph';
import type { GraphApiDocument, GraphPage } from '@supermemory/memory-graph';
import { useCallback, useEffect, useState } from 'react';
export default function PaginatedGraph() {
const [documents, setDocuments] = useState<GraphApiDocument[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchPage = useCallback(async (after: string | null) => {
const res = await fetch(after ? `/api/graph?cursor=${encodeURIComponent(after)}` : '/api/graph');
if (!res.ok) throw new Error(`Graph request failed: ${res.status}`);
const page: GraphPage = await res.json();
const next = graphPageToDocuments(page);
setDocuments(prev => (after ? [...prev, ...next] : next));
setCursor(page.nextCursor);
}, []);
useEffect(() => {
fetchPage(null)
.catch(setError)
.finally(() => setIsLoading(false));
}, [fetchPage]);
const loadMore = useCallback(async () => {
if (!cursor || isLoadingMore) return;
setIsLoadingMore(true);
try {
await fetchPage(cursor);
} catch (err) {
setError(err as Error);
} finally {
setIsLoadingMore(false);
}
}, [cursor, isLoadingMore, fetchPage]);
return (
<MemoryGraph
documents={documents}
isLoading={isLoading}
isLoadingMore={isLoadingMore}
error={error}
hasMore={cursor !== null}
onLoadMore={loadMore}
/>
);
}
```
### Highlighting search results
```tsx
<MemoryGraph
documents={documents}
highlightDocumentIds={searchResults}
highlightsVisible={searchResults.length > 0}
/>
```
### Custom empty state
```tsx
<MemoryGraph documents={documents} isLoading={isLoading}>
<div style={{ textAlign: 'center', padding: '2rem' }}>
<h2>No memories yet</h2>
<p>Add content to see your knowledge graph</p>
</div>
</MemoryGraph>
```
---
## Props reference
### Core props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `endpoint` | `string` | - | Your server route; fetched with `POST` and rendered with loading, empty and error states |
| `documents` | `GraphApiDocument[]` | `[]` | Documents to display, when you fetch them yourself |
| `isLoading` | `boolean` | `false` | Shows loading indicator |
| `error` | `Error \| null` | `null` | Error to display |
| `variant` | `"console" \| "consumer"` | `"console"` | Visual variant |
| `children` | `ReactNode` | - | Custom empty state content |
### Pagination props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `isLoadingMore` | `boolean` | `false` | Shows indicator when loading more |
| `hasMore` | `boolean` | `false` | Whether more documents available |
| `onLoadMore` | `() => void` | - | Called to load more, for example when the user zooms out past the loaded nodes |
| `totalCount` | `number` | - | Total document count shown by the loading indicator |
### Display props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `highlightDocumentIds` | `string[]` | `[]` | Document IDs to highlight |
| `highlightsVisible` | `boolean` | `true` | Whether highlights shown |
| `maxNodes` | `number` | - | Maximum number of nodes to display |
| `colors` | `Partial<GraphThemeColors>` | - | Theme color overrides |
| `labels` | `MemoryGraphLabels` | - | User-facing label overrides |
| `appearance` | `GraphAppearance` | - | Opt-in document node and connection styles (see above) |
| `openDocumentOnEnter` | `boolean` | `false` | Enable the Enter action that calls `onOpenDocument` |
| `onOpenDocument` | `(documentId: string) => void` | - | Called when the user opens a document |
---
## Data types
### GraphApiDocument
```typescript
interface GraphApiDocument {
id: string;
title: string | null;
summary: string | null;
documentType: string;
createdAt: string;
updatedAt: string;
memories: GraphApiMemory[];
}
```
### GraphApiMemory
```typescript
interface GraphApiMemory {
id: string;
memory: string;
content?: string | null;
isStatic: boolean;
spaceId: string;
isLatest: boolean;
isForgotten: boolean;
forgetAfter: string | null;
forgetReason: string | null;
version: number;
parentMemoryId: string | null;
rootMemoryId: string | null;
createdAt: string;
updatedAt: string;
relation?: 'updates' | 'extends' | 'derives' | null;
updatesMemoryId?: string | null;
nextVersionId?: string | null;
memoryRelations?: Record<string, 'updates' | 'extends' | 'derives'> | null;
spaceContainerTag?: string | null;
}
```
### GraphPage
One page of `POST /ns/{namespace}/graph`: `{ nodes, edges, nextCursor }`. `graphPageToDocuments(page)` turns it into `GraphApiDocument[]`.
`DocumentWithMemories` and `MemoryEntry` are still exported as backward-compatible types.
---
## Exports
### Components
```typescript
import { MemoryGraph, GraphCanvas } from '@supermemory/memory-graph';
```
### Server
```typescript
import { fetchMemoryGraph, MemoryGraphError } from '@supermemory/memory-graph/server';
```
### Adapters
```typescript
import { graphPageToDocuments } from '@supermemory/memory-graph';
```
### Hooks
```typescript
import { useGraphData, useGraphTheme } from '@supermemory/memory-graph';
```
### Engine classes
```typescript
import {
ForceSimulation,
ViewportState,
SpatialIndex,
VersionChainIndex
} from '@supermemory/memory-graph';
```
### Constants
```typescript
import {
DEFAULT_COLORS,
DEFAULT_HOVER_POPOVER_Z_INDEX,
DEFAULT_LABELS,
FORCE_CONFIG,
GRAPH_SETTINGS
} from '@supermemory/memory-graph';
```
---
## Performance
The graph handles hundreds of nodes efficiently through:
- Canvas-based rendering (not DOM elements)
- Viewport culling (only draws visible nodes)
- Level-of-detail optimization (simplifies when zoomed out)
- Change-based rendering (only redraws when state changes)
For very large datasets (1000+ documents), use pagination to load data in chunks.
## Browser support
Works in all modern browsers supporting Canvas 2D API, ES2020, and CSS custom properties. Tested on Chrome, Firefox, Safari, and Edge.