aboutsummaryrefslogtreecommitdiff
path: root/apps/docs/memory-graph/quick-start.mdx
blob: 295f82bfdc73cdbbf770f3610ec9ec1ce1b9098a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
---
title: "Quick Start"
description: "Build your first knowledge graph in 5 minutes"
sidebarTitle: "Quick Start"
---

Get your first interactive memory graph up and running in just a few minutes.

<Warning>
**Security First**: Never expose your Supermemory API key in client-side code. Always use a backend proxy to authenticate requests.
</Warning>

## Step 1: Create Backend Proxy

Create an API route in your backend that authenticates users and proxies requests to the Supermemory API.

<CodeGroup>

```typescript Next.js App Router
// app/api/supermemory-graph/route.ts
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  // Add your authentication logic here
  const user = await getAuthenticatedUser(request)
  if (!user) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { status: 401 }
    )
  }

  try {
    const response = await fetch(
      'https://api.supermemory.ai/v3/documents/documents',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
        },
        body: JSON.stringify({
          page: 1,
          limit: 500,
          sort: 'createdAt',
          order: 'desc',
          // Optional: Filter by user-specific container
          containerTags: [user.id],
        }),
      }
    )

    if (!response.ok) {
      throw new Error('Failed to fetch documents')
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Error fetching graph data:', error)
    return NextResponse.json(
      { error: 'Failed to fetch data' },
      { status: 500 }
    )
  }
}
```

```typescript Next.js Pages Router
// pages/api/supermemory-graph.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Add your authentication logic here
  const user = await getAuthenticatedUser(req)
  if (!user) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  try {
    const response = await fetch(
      'https://api.supermemory.ai/v3/documents/documents',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
        },
        body: JSON.stringify({
          page: 1,
          limit: 500,
          sort: 'createdAt',
          order: 'desc',
          containerTags: [user.id],
        }),
      }
    )

    const data = await response.json()
    res.status(200).json(data)
  } catch (error) {
    console.error('Error fetching graph data:', error)
    res.status(500).json({ error: 'Failed to fetch data' })
  }
}
```

</CodeGroup>

<Tip>
Use `containerTags` to filter documents by user in multi-user applications. This ensures users only see their own data.
</Tip>

## Step 2: Create Frontend Component

Create a component that fetches data and renders the graph.

```tsx GraphComponent.tsx
'use client' // Required for Next.js App Router

import { MemoryGraph } from '@supermemory/memory-graph'
import { useState, useEffect } from 'react'
import type { DocumentWithMemories } from '@supermemory/memory-graph'

export default function GraphComponent() {
  const [documents, setDocuments] = useState<DocumentWithMemories[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    fetch('/api/supermemory-graph')
      .then(async (res) => {
        if (!res.ok) {
          throw new Error('Failed to fetch documents')
        }
        return res.json()
      })
      .then((data) => {
        setDocuments(data.documents)
        setIsLoading(false)
      })
      .catch((err) => {
        setError(err)
        setIsLoading(false)
      })
  }, [])

  return (
    {/* CRITICAL: Container must have explicit width and height */}
    <div style={{ width: '100%', height: '100vh' }}>
      <MemoryGraph
        documents={documents}
        isLoading={isLoading}
        error={error}
      >
        {/* Custom empty state when no documents exist */}
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100%',
          gap: '1rem'
        }}>
          <h2>No memories yet</h2>
          <p>Start adding content to see your knowledge graph</p>
        </div>
      </MemoryGraph>
    </div>
  )
}
```

<Warning>
**Container Sizing**: The graph component requires its parent container to have explicit width and height. Without this, the canvas will have 0 dimensions and won't render.
</Warning>

## Step 3: Add to Your Page

Use the component in your page:

<CodeGroup>

```tsx Next.js App Router
// app/graph/page.tsx
import GraphComponent from '@/components/GraphComponent'

export default function GraphPage() {
  return (
    <main style={{ height: '100vh' }}>
      <GraphComponent />
    </main>
  )
}
```

```tsx Next.js Pages Router
// pages/graph.tsx
import GraphComponent from '@/components/GraphComponent'

export default function GraphPage() {
  return (
    <div style={{ height: '100vh' }}>
      <GraphComponent />
    </div>
  )
}
```

```tsx React SPA
// src/App.tsx
import GraphComponent from './components/GraphComponent'

function App() {
  return (
    <div className="App" style={{ height: '100vh' }}>
      <GraphComponent />
    </div>
  )
}

export default App
```

</CodeGroup>

## Complete Example

Here's a complete, production-ready example with proper error handling and loading states:

```tsx
'use client'

import { MemoryGraph } from '@supermemory/memory-graph'
import { useState, useEffect } from 'react'
import type { DocumentWithMemories } from '@supermemory/memory-graph'

export default function GraphDashboard() {
  const [documents, setDocuments] = useState<DocumentWithMemories[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/api/supermemory-graph')

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }

        const data = await response.json()
        setDocuments(data.documents || [])
      } catch (err) {
        console.error('Failed to fetch graph data:', err)
        setError(err instanceof Error ? err : new Error('Unknown error'))
      } finally {
        setIsLoading(false)
      }
    }

    fetchData()
  }, [])

  return (
    <div className="dashboard" style={{
      width: '100%',
      height: '100vh',
      position: 'relative'
    }}>
      <MemoryGraph
        documents={documents}
        isLoading={isLoading}
        error={error}
        variant="console"
      >
        <div className="empty-state">
          <h2>No memories yet</h2>
          <p>Start adding content to visualize your knowledge graph</p>
          <button onClick={() => window.location.href = '/add-memory'}>
            Add Your First Memory
          </button>
        </div>
      </MemoryGraph>
    </div>
  )
}
```

## Next Steps

<CardGroup cols={3}>
  <Card title="API Reference" icon="book" href="/memory-graph/api-reference">
    Explore all props and customization options
  </Card>

  <Card title="Examples" icon="code" href="/memory-graph/examples">
    See advanced patterns like pagination and highlighting
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/memory-graph/troubleshooting">
    Solve common issues
  </Card>
</CardGroup>