···11+# Tutorial
22+33+In this guide, we're going to build a **simple multi-user app** that publishes your current "status" as an emoji.
44+55+At various points we will cover how to:
66+77+- Signin via OAuth
88+- Fetch information about users (profiles)
99+- Listen to the network firehose for new data
1010+- Publish data on the user's account using a custom schema
1111+1212+We're going to keep this light so you can quickly wrap your head around ATProto. There will be links with more information about each step.
1313+1414+## Where are we going?
1515+1616+Data in the Atmosphere is stored on users' personal repos. It's almost like each user has their own website. Our goal is to aggregate data from the users into our SQLite DB.
1717+1818+Think of our app like a Google. If Google's job was to say which emoji each website had under `/status.json`, then it would show something like:
1919+2020+- `nytimes.com` is feeling 📰 according to `https://nytimes.com/status.json`
2121+- `bsky.app` is feeling 🦋 according to `https://bsky.app/status.json`
2222+- `reddit.com` is feeling 🤓 according to `https://reddit.com/status.json`
2323+2424+The Atmosphere works the same way, except we're going to check `at://` instead of `https://`. Each user has a data repo under an `at://` URL. We'll crawl all the `at://`s in the Atmosphere for all the `/status.json` records and aggregate them into our SQLite database.
2525+2626+## Step 1. Starting with our ExpressJS app
2727+2828+Start by cloning the repo and installing packages.
2929+3030+```bash
3131+git clone TODO
3232+cd TODO
3333+npm i
3434+npm run dev # you can leave this running and it will auto-reload
3535+```
3636+3737+Our repo is a regular Web app. We're rendering our HTML server-side like it's 1999. We also have a SQLite database that we're managing with [Kysley](#todo).
3838+3939+Our starting stack:
4040+4141+- Typescript
4242+- NodeJS web server ([express](#todo))
4343+- SQLite database ([Kysley](#todo))
4444+- Server-side rendering ([uhtml](#todo))
4545+4646+With each step we'll explain how our Web app taps into the Atmosphere. Refer to the codebase for more detailed code — again, this tutorial is going to keep it light and quick to digest.
4747+4848+## Step 2. Signing in with OAuth
4949+5050+When somebody logs into our app, they'll give us read & write access to their personal `at://` repo. We'll use that to write the `status.json` record.
5151+5252+We're going to accomplish this using OAuth ([spec](#todo)). You can find a [more extensive OAuth guide here](#todo), but for now just know that most of the OAuth flows are going to be handled for us using the [@atproto/oauth-client-node](#todo) library. This is the arrangement we're aiming toward:
5353+5454+```
5555+ ┌─App Server───────────────────┐
5656+ │ ┌─► Session store ◄┐ │
5757+ │ │ │ │ ┌───────────────┐
5858+ │ App code ──────►OAuth client─┼───►│ User's server │
5959+ └────▲─────────────────────────┘ └───────────────┘
6060+ ┌────┴──────────┐
6161+ │ Web browser │
6262+ └───────────────┘
6363+```
6464+6565+When the user logs in, the OAuth client will create a new session with their repo server and give us read/write access along with basic user info.
6666+6767+Our login page just asks the user for their "handle," which is the domain name associated with their account. For [Bluesky](https://bsky.app) users, these tend to look like `alice.bsky.social`, but they can be any kind of domain (eg `alice.com`).
6868+6969+```html
7070+<!-- src/pages/login.ts -->
7171+<form action="/login" method="post" class="login-form">
7272+ <input
7373+ type="text"
7474+ name="handle"
7575+ placeholder="Enter your handle (eg alice.bsky.social)"
7676+ required
7777+ />
7878+ <button type="submit">Log in</button>
7979+</form>
8080+```
8181+8282+When they submit the form, we tell our OAuth client to initiate the authorization flow and then redirect the user to their server to complete the process.
8383+8484+```typescript
8585+/** src/routes.ts **/
8686+// Login handler
8787+router.post(
8888+ '/login',
8989+ handler(async (req, res) => {
9090+ // Initiate the OAuth flow
9191+ const url = await oauthClient.authorize(handle)
9292+ return res.redirect(url.toString())
9393+ })
9494+)
9595+```
9696+9797+This is the same kind of SSO flow that Google or GitHub uses. The user will be asked for their password, then asked to confirm the session with your application.
9898+9999+When that finishes, they'll be sent back to `/oauth/callback` on our Web app. The OAuth client stores the access tokens for the server, and then we attach their account's [DID](#todo) to their cookie-session.
100100+101101+```typescript
102102+/** src/routes.ts **/
103103+// OAuth callback to complete session creation
104104+router.get(
105105+ '/oauth/callback',
106106+ handler(async (req, res) => {
107107+ // Store the credentials
108108+ const { agent } = await oauthClient.callback(params)
109109+110110+ // Attach the account DID to our user via a cookie
111111+ const session = await getIronSession(req, res)
112112+ session.did = agent.accountDid
113113+ await session.save()
114114+115115+ // Send them back to the app
116116+ return res.redirect('/')
117117+ })
118118+)
119119+```
120120+121121+With that, we're in business! We now have a session with the user's `at://` repo server and can use that to access their data.
122122+123123+## Step 3. Fetching the user's profile
124124+125125+Why don't we learn something about our user? Let's start by getting the [Agent](#todo) object. The [Agent](#todo) is the client to the user's `at://` repo server.
126126+127127+```typescript
128128+/** src/routes.ts **/
129129+async function getSessionAgent(
130130+ req: IncomingMessage,
131131+ res: ServerResponse<IncomingMessage>,
132132+ ctx: AppContext
133133+) {
134134+ // Fetch the session from their cookie
135135+ const session = await getIronSession(req, res)
136136+ if (!session.did) return null
137137+138138+ // "Restore" the agent for the user
139139+ return await ctx.oauthClient.restore(session.did).catch(async (err) => {
140140+ ctx.logger.warn({ err }, 'oauth restore failed')
141141+ await session.destroy()
142142+ return null
143143+ })
144144+}
145145+```
146146+147147+Users publish JSON records on their `at://` repos. In [Bluesky](https://bsky.app), they publish a "profile" record which looks like this:
148148+149149+```typescript
150150+interface ProfileRecord {
151151+ displayName?: string // a human friendly name
152152+ description?: string // a short bio
153153+ avatar?: BlobRef // small profile picture
154154+ banner?: BlobRef // banner image to put on profiles
155155+ createdAt?: string // declared time this profile data was added
156156+ // ...
157157+}
158158+```
159159+160160+We're going to use the [Agent](#todo) to fetch this record to include in our app.
161161+162162+```typescript
163163+/** src/routes.ts **/
164164+// Homepage
165165+router.get(
166166+ '/',
167167+ handler(async (req, res) => {
168168+ // If the user is signed in, get an agent which communicates with their server
169169+ const agent = await getSessionAgent(req, res, ctx)
170170+171171+ if (!agent) {
172172+ // Serve the logged-out view
173173+ return res.type('html').send(page(home()))
174174+ }
175175+176176+ // Fetch additional information about the logged-in user
177177+ const { data: profileRecord } = await agent.getRecord({
178178+ repo: agent.accountDid, // our user's repo
179179+ collection: 'app.bsky.actor.profile', // the bluesky profile record type
180180+ rkey: 'self', // the record's name
181181+ })
182182+183183+ // Serve the logged-in view
184184+ return res
185185+ .type('html')
186186+ .send(page(home({ profile: profileRecord.value || {} })))
187187+ })
188188+)
189189+```
190190+191191+With that data, we can give a nice personalized welcome banner for our user:
192192+193193+```html
194194+<!-- pages/home.ts -->
195195+<div class="card">
196196+ ${profile
197197+ ? html`<form action="/logout" method="post" class="session-form">
198198+ <div>
199199+ Hi, <strong>${profile.displayName || 'friend'}</strong>.
200200+ What's your status today?
201201+ </div>
202202+ <div>
203203+ <button type="submit">Log out</button>
204204+ </div>
205205+ </form>`
206206+ : html`<div class="session-form">
207207+ <div><a href="/login">Log in</a> to set your status!</div>
208208+ <div>
209209+ <a href="/login" class="button">Log in</a>
210210+ </div>
211211+ </div>`}
212212+</div>
213213+```
214214+215215+## Step 4. Reading & writing records
216216+217217+You can think of the user repositories as collections of JSON records:
218218+219219+```
220220+ ┌────────┐
221221+ ┌───| record │
222222+ ┌────────────┐ │ └────────┘
223223+ ┌───| collection |◄─┤ ┌────────┐
224224+┌──────┐ │ └────────────┘ └───| record │
225225+│ repo |◄──┤ └────────┘
226226+└──────┘ │ ┌────────────┐ ┌────────┐
227227+ └───┤ collection |◄─────| record │
228228+ └────────────┘ └────────┘
229229+```
230230+231231+Let's look again at how we read the "profile" record:
232232+233233+```typescript
234234+await agent.getRecord({
235235+ repo: agent.accountDid, // The user
236236+ collection: 'app.bsky.actor.profile', // The collection
237237+ rkey: 'self', // The record name
238238+})
239239+```
240240+241241+We write records using a similar API. Since our goal is to write "status" records, let's look at how that will happen:
242242+243243+```typescript
244244+await agent.putRecord({
245245+ repo: agent.accountDid, // The user
246246+ collection: 'com.example.status', // The collection
247247+ rkey: 'self', // The record name
248248+ record: { // The record value
249249+ status: "👍",
250250+ updatedAt: new Date().toISOString()
251251+ }
252252+})
253253+```
254254+255255+Our `POST /status` route is going to use this API to publish the user's status to their repo.
256256+257257+```typescript
258258+/** src/routes.ts **/
259259+// "Set status" handler
260260+router.post(
261261+ '/status',
262262+ handler(async (req, res) => {
263263+ // If the user is signed in, get an agent which communicates with their server
264264+ const agent = await getSessionAgent(req, res, ctx)
265265+ if (!agent) {
266266+ return res.status(401).json({ error: 'Session required' })
267267+ }
268268+269269+ // Construct their status record
270270+ const record = {
271271+ $type: 'com.example.status',
272272+ status: req.body?.status,
273273+ updatedAt: new Date().toISOString(),
274274+ }
275275+276276+ try {
277277+ // Write the status record to the user's repository
278278+ await agent.putRecord({
279279+ repo: agent.accountDid,
280280+ collection: 'com.example.status',
281281+ rkey: 'self',
282282+ record,
283283+ })
284284+ } catch (err) {
285285+ ctx.logger.warn({ err }, 'failed to write record')
286286+ return res.status(500).json({ error: 'Failed to write record' })
287287+ }
288288+289289+ res.status(200).json({})
290290+ })
291291+)
292292+```
293293+294294+Now in our homepage we can list out the status buttons:
295295+296296+```html
297297+<!-- src/pages/home.ts -->
298298+<div class="status-options">
299299+ ${['👍', '🦋', '🥳', /*...*/].map(status => html`
300300+ <div class="status-option" data-value="${status}">
301301+ ${status}
302302+ </div>`
303303+ )}
304304+</div>
305305+```
306306+307307+And write some client-side javascript to submit the status on click:
308308+309309+```javascript
310310+/* src/pages/public/home.js */
311311+Array.from(document.querySelectorAll('.status-option'), (el) => {
312312+ el.addEventListener('click', async (ev) => {
313313+ const res = await fetch('/status', {
314314+ method: 'POST',
315315+ headers: { 'content-type': 'application/json' },
316316+ body: JSON.stringify({ status: el.dataset.value }),
317317+ })
318318+ const body = await res.json()
319319+ if (!body?.error) {
320320+ location.reload()
321321+ }
322322+ })
323323+})
324324+```
325325+326326+## Step 5. Creating a custom "status" schema
327327+328328+The collections are typed, meaning that they have a defined schema. The `app.bsky.actor.profile` type definition [can be found here](https://github.com/bluesky-social/atproto/blob/main/lexicons/app/bsky/actor/profile.json).
329329+330330+Anybody can create a new schema using the [Lexicon](#todo) language, which is very similar to [JSON-Schema](#todo). The schemas use [reverse-DNS IDs](#todo) which indicate ownership, but for this demo app we're going to use `com.example` which is safe for non-production software.
331331+332332+> ### Why create a schema?
333333+>
334334+> Schemas help other applications understand the data your app is creating. By publishing your schemas, you enable compatibility and reduce the chances of bad data affecting your app.
335335+336336+Let's create our schema in the `/lexicons` folder of our codebase. You can [read more about how to define schemas here](#todo).
337337+338338+```json
339339+/* lexicons/status.json */
340340+{
341341+ "lexicon": 1,
342342+ "id": "com.example.status",
343343+ "defs": {
344344+ "main": {
345345+ "type": "record",
346346+ "key": "literal:self",
347347+ "record": {
348348+ "type": "object",
349349+ "required": ["status", "updatedAt"],
350350+ "properties": {
351351+ "status": {
352352+ "type": "string",
353353+ "minLength": 1,
354354+ "maxGraphemes": 1,
355355+ "maxLength": 32
356356+ },
357357+ "updatedAt": {
358358+ "type": "string",
359359+ "format": "datetime"
360360+ }
361361+ }
362362+ }
363363+ }
364364+ }
365365+}
366366+```
367367+368368+Now let's run some code-generation using our schema:
369369+370370+```bash
371371+./node_modules/.bin/lex gen-server ./src/lexicon ./lexicons/*
372372+```
373373+374374+This will produce Typescript interfaces as well as runtime validation functions that we can use in our `POST /status` route:
375375+376376+```typescript
377377+/** src/routes.ts **/
378378+import * as Status from '#/lexicon/types/com/example/status'
379379+// ...
380380+// "Set status" handler
381381+router.post(
382382+ '/status',
383383+ handler(async (req, res) => {
384384+ // ...
385385+386386+ // Construct & validate their status record
387387+ const record = {
388388+ $type: 'com.example.status',
389389+ status: req.body?.status,
390390+ updatedAt: new Date().toISOString(),
391391+ }
392392+ if (!Status.validateRecord(record).success) {
393393+ return res.status(400).json({ error: 'Invalid status' })
394394+ }
395395+396396+ // ...
397397+ })
398398+)
399399+```
400400+401401+## Step 6. Listening to the firehose
402402+403403+So far, we have:
404404+405405+- Logged in via OAuth
406406+- Created a custom schema
407407+- Read & written records for the logged in user
408408+409409+Now we want to fetch the status records from other users.
410410+411411+Remember how we referred to our app as being like a Google, crawling around the repos to get their records? One advantage we have in the AT Protocol is that each repo publishes an event log of their updates.
412412+413413+```
414414+┌──────┐
415415+│ REPO │ Event stream
416416+├──────┘
417417+│ ┌───────────────────────────────────────────┐
418418+├───┼ 1 PUT /com.example.status/self │
419419+│ └───────────────────────────────────────────┘
420420+│ ┌───────────────────────────────────────────┐
421421+├───┼ 2 DEL /app.bsky.feed.post/3l244rmrxjx2v │
422422+│ └───────────────────────────────────────────┘
423423+│ ┌───────────────────────────────────────────┐
424424+├───┼ 3 PUT /app.bsky.actor/self │
425425+▼ └───────────────────────────────────────────┘
426426+```
427427+428428+Using a [Relay service](#todo) we can listen to an aggregated firehose of these events across all users in the network. In our case what we're looking for are valid `com.example.status` records.
429429+430430+431431+```typescript
432432+/** src/firehose.ts **/
433433+import * as Status from '#/lexicon/types/com/example/status'
434434+// ...
435435+const firehose = new Firehose({})
436436+437437+for await (const evt of firehose.run()) {
438438+ // Watch for write events
439439+ if (evt.event === 'create' || evt.event === 'update') {
440440+ const record = evt.record
441441+442442+ // If the write is a valid status update
443443+ if (
444444+ evt.collection === 'com.example.status' &&
445445+ Status.isRecord(record) &&
446446+ Status.validateRecord(record).success
447447+ ) {
448448+ // Store the status
449449+ // TODO
450450+ }
451451+ }
452452+}
453453+```
454454+455455+Let's create a SQLite table to store these statuses:
456456+457457+```typescript
458458+/** src/db.ts **/
459459+// Create our statuses table
460460+await db.schema
461461+ .createTable('status')
462462+ .addColumn('authorDid', 'varchar', (col) => col.primaryKey())
463463+ .addColumn('status', 'varchar', (col) => col.notNull())
464464+ .addColumn('updatedAt', 'varchar', (col) => col.notNull())
465465+ .addColumn('indexedAt', 'varchar', (col) => col.notNull())
466466+ .execute()
467467+```
468468+469469+Now we can write these statuses into our database as they arrive from the firehose:
470470+471471+```typescript
472472+/** src/firehose.ts **/
473473+// If the write is a valid status update
474474+if (
475475+ evt.collection === 'com.example.status' &&
476476+ Status.isRecord(record) &&
477477+ Status.validateRecord(record).success
478478+) {
479479+ // Store the status in our SQLite
480480+ await db
481481+ .insertInto('status')
482482+ .values({
483483+ authorDid: evt.author,
484484+ status: record.status,
485485+ updatedAt: record.updatedAt,
486486+ indexedAt: new Date().toISOString(),
487487+ })
488488+ .onConflict((oc) =>
489489+ oc.column('authorDid').doUpdateSet({
490490+ status: record.status,
491491+ updatedAt: record.updatedAt,
492492+ indexedAt: new Date().toISOString(),
493493+ })
494494+ )
495495+ .execute()
496496+}
497497+```
498498+499499+You can almost think of information flowing in a loop:
500500+501501+```
502502+ ┌─────Repo put─────┐
503503+ │ ▼
504504+┌──────┴─────┐ ┌───────────┐
505505+│ App server │ │ User repo │
506506+└────────────┘ └─────┬─────┘
507507+ ▲ │
508508+ └────Event log─────┘
509509+```
510510+511511+Why read from the event log? Because there are other apps in the network that will write the records we're interested in. By subscribing to the event log, we ensure that we catch all the data we're interested in -- including data published by other apps.
512512+513513+## Step 7. Listing the latest statuses
514514+515515+Now that we have statuses populating our SQLite, we can produce a timeline of status updates by users. We also use a [DID](#todo)-to-handle resolver so we can show a nice username with the statuses:
516516+517517+```typescript
518518+/** src/routes.ts **/
519519+// Homepage
520520+router.get(
521521+ '/',
522522+ handler(async (req, res) => {
523523+ // ...
524524+525525+ // Fetch data stored in our SQLite
526526+ const statuses = await db
527527+ .selectFrom('status')
528528+ .selectAll()
529529+ .orderBy('indexedAt', 'desc')
530530+ .limit(10)
531531+ .execute()
532532+533533+ // Map user DIDs to their domain-name handles
534534+ const didHandleMap = await resolver.resolveDidsToHandles(
535535+ statuses.map((s) => s.authorDid)
536536+ )
537537+538538+ // ...
539539+ })
540540+)
541541+```
542542+543543+Our HTML can now list these status records:
544544+545545+```html
546546+<!-- src/pages/home.ts -->
547547+${statuses.map((status, i) => {
548548+ const handle = didHandleMap[status.authorDid] || status.authorDid
549549+ const date = ts(status)
550550+ return html`
551551+ <div class="status-line">
552552+ <div>
553553+ <div class="status">${status.status}</div>
554554+ </div>
555555+ <div class="desc">
556556+ <a class="author" href="https://bsky.app/profile/${handle}">@${handle}</a>
557557+ was feeling ${status.status} on ${status.indexedAt}.
558558+ </div>
559559+ </div>
560560+ `
561561+})}
562562+```
563563+564564+## Step 8. Optimistic updates
565565+566566+As a final optimization, let's introduce "optimistic updates." Remember the information flow loop with the repo write and the event log? Since we're updating our users' repos locally, we can short-circuit that flow to our own database:
567567+568568+```
569569+ ┌───Repo put──┬──────┐
570570+ │ │ ▼
571571+┌──────┴─────┐ │ ┌───────────┐
572572+│ App server │◄──────┘ │ User repo │
573573+└────────────┘ └───┬───────┘
574574+ ▲ │
575575+ └────Event log───────┘
576576+```
577577+578578+This is an important optimization to make, because it ensures that the user sees their own changes while using your app. When the event eventually arrives from the firehose, we just discard it since we already have it saved locally.
579579+580580+To do this, we just update `POST /status` to include an additional write to our SQLite DB:
581581+582582+```typescript
583583+/** src/routes.ts **/
584584+// "Set status" handler
585585+router.post(
586586+ '/status',
587587+ handler(async (req, res) => {
588588+ // ...
589589+590590+ try {
591591+ // Write the status record to the user's repository
592592+ await agent.putRecord({
593593+ repo: agent.accountDid,
594594+ collection: 'com.example.status',
595595+ rkey: 'self',
596596+ record,
597597+ })
598598+ } catch (err) {
599599+ ctx.logger.warn({ err }, 'failed to write record')
600600+ return res.status(500).json({ error: 'Failed to write record' })
601601+ }
602602+603603+ try {
604604+ // Optimistically update our SQLite <-- HERE!
605605+ await ctx.db
606606+ .insertInto('status')
607607+ .values({
608608+ authorDid: agent.accountDid,
609609+ status: record.status,
610610+ updatedAt: record.updatedAt,
611611+ indexedAt: new Date().toISOString(),
612612+ })
613613+ .onConflict((oc) =>
614614+ oc.column('authorDid').doUpdateSet({
615615+ status: record.status,
616616+ updatedAt: record.updatedAt,
617617+ indexedAt: new Date().toISOString(),
618618+ })
619619+ )
620620+ .execute()
621621+ } catch (err) {
622622+ ctx.logger.warn(
623623+ { err },
624624+ 'failed to update computed view; ignoring as it should be caught by the firehose'
625625+ )
626626+ }
627627+628628+ res.status(200).json({})
629629+ })
630630+)
631631+```
632632+633633+You'll notice this code looks almost exactly like what we're doing in `firehose.ts`.
634634+635635+## Next steps
636636+637637+TODO
638638+639639+640640+641641+---
642642+643643+Let's create the client during the server init:
644644+645645+```typescript
646646+/** index.ts **/
647647+import { NodeOAuthClient } from '@atproto/oauth-client-node'
648648+649649+// static async create() {
650650+// ...
651651+652652+const publicUrl = env.PUBLIC_URL
653653+const url = publicUrl || `http://127.0.0.1:${env.PORT}`
654654+const oauthClient = new NodeOAuthClient({
655655+ clientMetadata: {
656656+ client_name: 'AT Protocol Express App',
657657+ client_id: publicUrl
658658+ ? `${url}/client-metadata.json`
659659+ : `http://localhost?redirect_uri=${encodeURIComponent(`${url}/oauth/callback`)}`,
660660+ client_uri: url,
661661+ redirect_uris: [`${url}/oauth/callback`],
662662+ scope: 'profile offline_access',
663663+ grant_types: ['authorization_code', 'refresh_token'],
664664+ response_types: ['code'],
665665+ application_type: 'web',
666666+ token_endpoint_auth_method: 'none',
667667+ dpop_bound_access_tokens: true,
668668+ },
669669+ stateStore: new StateStore(db),
670670+ sessionStore: new SessionStore(db),
671671+})
672672+673673+// ...
674674+// }
675675+```
676676+677677+There's quite a bit of configuration which is [explained in the OAuth guide](#todo). We host that config at `/client-metadata.json` as part of the OAuth flow.
678678+679679+```typescript
680680+/** src/routes.ts **/
681681+682682+// OAuth metadata
683683+router.get(
684684+ '/client-metadata.json',
685685+ handler((_req, res) => {
686686+ return res.json(oauthClient.clientMetadata)
687687+ })
688688+)
689689+```
690690+691691+---
692692+693693+694694+695695+We're going to need to track two kinds of information:
696696+697697+- **OAuth State**. This is information about login flows that are in-progress.
698698+- **OAuth Sessions**. This is the active session data.
699699+700700+The `oauth-client-node` library handles most of this for us, but we need to create some tables in our SQLite to store it. Let's update `/src/db.ts` for this.
701701+702702+```typescript
703703+// ...
704704+// Types
705705+706706+export type DatabaseSchema = {
707707+ auth_session: AuthSession
708708+ auth_state: AuthState
709709+}
710710+711711+export type AuthSession = {
712712+ key: string
713713+ session: string // JSON
714714+}
715715+716716+export type AuthState = {
717717+ key: string
718718+ state: string // JSON
719719+}
720720+721721+// Migrations
722722+723723+migrations['001'] = {
724724+ async up(db: Kysely<unknown>) {
725725+ await db.schema
726726+ .createTable('auth_session')
727727+ .addColumn('key', 'varchar', (col) => col.primaryKey())
728728+ .addColumn('session', 'varchar', (col) => col.notNull())
729729+ .execute()
730730+ await db.schema
731731+ .createTable('auth_state')
732732+ .addColumn('key', 'varchar', (col) => col.primaryKey())
733733+ .addColumn('state', 'varchar', (col) => col.notNull())
734734+ .execute()
735735+ },
736736+ async down(db: Kysely<unknown>) {
737737+ await db.schema.dropTable('auth_state').execute()
738738+ await db.schema.dropTable('auth_session').execute()
739739+ },
740740+}
741741+742742+// ...
743743+```
744744+745745+746746+----
747747+748748+749749+Data in the Atmosphere is stored on users' personal servers. It's almost like each user has their own website. Our goal is to aggregate data from the users into our SQLite.
750750+751751+Think of our app like a Google. If Google's job was to say which emoji each website had under `/status.txt`, then it would show something like:
752752+753753+- `nytimes.com` is feeling 📰 according to `https://nytimes.com/status.txt`
754754+- `bsky.app` is feeling 🦋 according to `https://bsky.app/status.txt`
755755+- `reddit.com` is feeling 🤓 according to `https://reddit.com/status.txt`
756756+757757+The Atmosphere works the same way, except we're going to check `at://nytimes.com/com.example.status/self`. Literally, that's it! Each user has a domain, and each record gets published under an atproto URL.
758758+759759+```
760760+AT Protocol
761761+ ▼
762762+at://nytimes.com/com.example.status/self
763763+ ▲ ▲ ▲
764764+ The user The data type The record name
765765+```
766766+767767+When somebody logs into our app, they'll give read & write access to their personal `at://`. We'll use that to write the `/com.example.status/self` record. Then we'll crawl the Atmosphere for all the other `/com.example.status/self` records, and aggregate them into our SQLite database for fast reads.
768768+769769+Believe it or not, that's how most apps on the Atmosphere are built, including [Bluesky](#todo).