The best way to control Claude Code, Codex and more from any computer or phone
| 1 | --- |
| 2 | title: Sign in with better-auth |
| 3 | description: Sign users in to a Domain Api with GitHub or Google through better-auth, and give every command and view the signed-in user. |
| 4 | --- |
| 5 | |
| 6 | [better-auth](https://better-auth.com) signs users in with GitHub, Google and many other providers, and keeps their sessions in your database. A Domain Api reads that session in middleware, so every command and view knows who is asking. |
| 7 | |
| 8 | This page builds a small notes app on Cloudflare, with a [foldkit](https://foldkit.dev) UI: users sign in with GitHub or Google and write notes only they can read. The whole app is in [`examples/cloudflare-domain-better-auth`](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain-better-auth). |
| 9 | |
| 10 | ## Install |
| 11 | |
| 12 | ```sh |
| 13 | bun add @alchemy.run/domain @alchemy.run/better-auth @alchemy.run/cloudflare better-auth |
| 14 | ``` |
| 15 | |
| 16 | ## Declare who is asking |
| 17 | |
| 18 | ```typescript |
| 19 | // src/User.id.ts |
| 20 | import * as Schema from "effect/Schema"; |
| 21 | |
| 22 | /** A user's id, as better-auth assigns it. */ |
| 23 | export const UserId = Schema.String.pipe(Schema.brand("UserId")); |
| 24 | export type UserId = typeof UserId.Type; |
| 25 | ``` |
| 26 | |
| 27 | ```typescript |
| 28 | // src/CurrentUser.context.ts |
| 29 | import * as Domain from "@alchemy.run/domain"; |
| 30 | import * as Schema from "effect/Schema"; |
| 31 | import { UserId } from "./User.id.ts"; |
| 32 | |
| 33 | /** The signed-in user behind a request. */ |
| 34 | export class CurrentUser extends Domain.RequestContext<CurrentUser>()( |
| 35 | "Notes/CurrentUser", |
| 36 | Schema.Struct({ userId: UserId, name: Schema.String }), |
| 37 | ) {} |
| 38 | ``` |
| 39 | |
| 40 | `CurrentUser` is the user behind a request. It has a schema, so it travels with each command to the notebook that decides it. |
| 41 | |
| 42 | ## Declare the middleware |
| 43 | |
| 44 | ```typescript |
| 45 | // src/Session.middleware.ts |
| 46 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 47 | import * as Schema from "effect/Schema"; |
| 48 | import { CurrentUser } from "./CurrentUser.context.ts"; |
| 49 | |
| 50 | /** The request has no session. */ |
| 51 | export class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {} |
| 52 | |
| 53 | /** Provides the signed-in user, from the session cookie better-auth set. */ |
| 54 | export class Session extends RpcMiddleware.Service<Session, { provides: CurrentUser }>()( |
| 55 | "Notes/Session", |
| 56 | { error: Unauthorized }, |
| 57 | ) {} |
| 58 | ``` |
| 59 | |
| 60 | `Session` provides `CurrentUser`, or fails with `Unauthorized`. The domain only declares it; the Worker implements it with better-auth below. |
| 61 | |
| 62 | ## Guard a command |
| 63 | |
| 64 | ```typescript |
| 65 | // src/NotYours.rejection.ts |
| 66 | import * as Domain from "@alchemy.run/domain"; |
| 67 | |
| 68 | /** The notebook belongs to someone else. */ |
| 69 | export class NotYours extends Domain.Rejection("NotYours") {} |
| 70 | ``` |
| 71 | |
| 72 | ```typescript |
| 73 | // src/WriteNote.command.ts |
| 74 | import * as Domain from "@alchemy.run/domain"; |
| 75 | import * as Schema from "effect/Schema"; |
| 76 | import { NotYours } from "./NotYours.rejection.ts"; |
| 77 | import { Session } from "./Session.middleware.ts"; |
| 78 | import { UserId } from "./User.id.ts"; |
| 79 | |
| 80 | export class NoteWritten extends Domain.Event("NoteWritten", { |
| 81 | text: Schema.String, |
| 82 | author: Schema.String, |
| 83 | }) {} |
| 84 | |
| 85 | /** Write a note in your own notebook. */ |
| 86 | export class WriteNote extends Domain.Command("WriteNote", { |
| 87 | target: UserId, |
| 88 | middleware: [Session], |
| 89 | input: { text: Schema.NonEmptyString }, |
| 90 | events: [NoteWritten], |
| 91 | rejects: [NotYours], |
| 92 | }) {} |
| 93 | ``` |
| 94 | |
| 95 | Listing `Session` makes the Api run it before every `WriteNote`. |
| 96 | |
| 97 | ## Check the user in decide |
| 98 | |
| 99 | ```typescript |
| 100 | // src/Notebook.aggregate.ts |
| 101 | import * as Domain from "@alchemy.run/domain"; |
| 102 | import * as Effect from "effect/Effect"; |
| 103 | import * as Schema from "effect/Schema"; |
| 104 | import { CurrentUser } from "./CurrentUser.context.ts"; |
| 105 | import { NotYours } from "./NotYours.rejection.ts"; |
| 106 | import { UserId } from "./User.id.ts"; |
| 107 | import { NoteWritten, WriteNote } from "./WriteNote.command.ts"; |
| 108 | |
| 109 | /** Each user's notebook, keyed by their id. */ |
| 110 | export class Notebook extends Domain.Aggregate("Notebook", { |
| 111 | id: UserId, |
| 112 | state: Schema.Struct({ notes: Schema.Int }), |
| 113 | initial: { notes: 0 }, |
| 114 | commands: [WriteNote], |
| 115 | decide: { |
| 116 | WriteNote: Effect.fn(function* (_s, cmd, { id }) { |
| 117 | const user = yield* CurrentUser; |
| 118 | if (user.userId !== id) return yield* new NotYours(); |
| 119 | return [new NoteWritten({ text: cmd.text, author: user.name })]; |
| 120 | }), |
| 121 | }, |
| 122 | evolve: { |
| 123 | NoteWritten: (s) => ({ notes: s.notes + 1 }), |
| 124 | }, |
| 125 | }) {} |
| 126 | ``` |
| 127 | |
| 128 | Each user has a notebook keyed by their id. `decide` reads `CurrentUser` and refuses a notebook that isn't theirs. |
| 129 | |
| 130 | ## Guard a view |
| 131 | |
| 132 | ```typescript |
| 133 | // src/Notes.view.ts |
| 134 | import * as Domain from "@alchemy.run/domain"; |
| 135 | import * as Effect from "effect/Effect"; |
| 136 | import * as Schema from "effect/Schema"; |
| 137 | import { CurrentUser } from "./CurrentUser.context.ts"; |
| 138 | import { Notebook } from "./Notebook.aggregate.ts"; |
| 139 | import { NotYours } from "./NotYours.rejection.ts"; |
| 140 | import { Session } from "./Session.middleware.ts"; |
| 141 | |
| 142 | /** The notes in a notebook. Only its owner may read them. */ |
| 143 | export class Notes extends Domain.View("Notes", { |
| 144 | from: [Notebook], |
| 145 | key: Notebook, |
| 146 | middleware: [Session], |
| 147 | rejects: [NotYours], |
| 148 | state: Schema.Struct({ notes: Schema.Array(Schema.String) }), |
| 149 | initial: { notes: [] }, |
| 150 | evolve: { |
| 151 | NoteWritten: (v, e) => ({ notes: [...v.notes, e.text] }), |
| 152 | }, |
| 153 | validate: Effect.fn(function* (request) { |
| 154 | const user = yield* CurrentUser; |
| 155 | if (request.key.id !== user.userId) return yield* new NotYours(); |
| 156 | }), |
| 157 | }) {} |
| 158 | ``` |
| 159 | |
| 160 | ```typescript |
| 161 | // src/Notes.model.ts |
| 162 | import * as Domain from "@alchemy.run/domain"; |
| 163 | import { Notebook } from "./Notebook.aggregate.ts"; |
| 164 | import { Notes } from "./Notes.view.ts"; |
| 165 | |
| 166 | export class NotesModel extends Domain.Model("Notes", { |
| 167 | aggregates: [Notebook], |
| 168 | views: [Notes], |
| 169 | }) {} |
| 170 | ``` |
| 171 | |
| 172 | ```typescript |
| 173 | // src/NotesApi.api.ts |
| 174 | import * as Domain from "@alchemy.run/domain"; |
| 175 | import { NotesModel } from "./Notes.model.ts"; |
| 176 | |
| 177 | /** What the browser reaches. */ |
| 178 | export class NotesApi extends Domain.Api("NotesApi", { |
| 179 | model: NotesModel, |
| 180 | commands: ["WriteNote"], |
| 181 | views: ["Notes"], |
| 182 | }) {} |
| 183 | ``` |
| 184 | |
| 185 | `validate` runs on every read, so only the owner reads a notebook's notes. |
| 186 | |
| 187 | ## Configure better-auth |
| 188 | |
| 189 | ```typescript |
| 190 | // src/Auth.ts |
| 191 | import { BetterAuth, type BetterAuthApiError } from "@alchemy.run/better-auth"; |
| 192 | import type { RuntimeContext } from "alchemy"; |
| 193 | import type { HttpEffect } from "alchemy/Http"; |
| 194 | import * as Config from "effect/Config"; |
| 195 | import * as Context from "effect/Context"; |
| 196 | import * as Effect from "effect/Effect"; |
| 197 | import * as Layer from "effect/Layer"; |
| 198 | import * as Option from "effect/Option"; |
| 199 | import * as Redacted from "effect/Redacted"; |
| 200 | |
| 201 | /** What the Worker needs from better-auth: its routes, and the session behind a request. */ |
| 202 | export class Auth extends Context.Service< |
| 203 | Auth, |
| 204 | { |
| 205 | readonly fetch: HttpEffect<RuntimeContext>; |
| 206 | readonly getSession: ( |
| 207 | headers: Headers, |
| 208 | ) => Effect.Effect< |
| 209 | { readonly user: { readonly id: string; readonly name: string } } | null, |
| 210 | BetterAuthApiError, |
| 211 | RuntimeContext |
| 212 | >; |
| 213 | } |
| 214 | >()("Notes/Auth") {} |
| 215 | |
| 216 | /** better-auth with GitHub and Google sign-in, its tables in the Worker's database. */ |
| 217 | export const AuthLive = Layer.effect( |
| 218 | Auth, |
| 219 | Effect.gen(function* () { |
| 220 | const baseURL = yield* Config.String("AUTH_BASE_URL").pipe(Config.option); |
| 221 | return yield* BetterAuth({ |
| 222 | basePath: "/api/auth", |
| 223 | baseURL: Option.getOrUndefined(baseURL), |
| 224 | socialProviders: { |
| 225 | github: { |
| 226 | clientId: yield* Config.String("GITHUB_CLIENT_ID"), |
| 227 | clientSecret: Redacted.value(yield* Config.Redacted("GITHUB_CLIENT_SECRET")), |
| 228 | }, |
| 229 | google: { |
| 230 | clientId: yield* Config.String("GOOGLE_CLIENT_ID"), |
| 231 | clientSecret: Redacted.value(yield* Config.Redacted("GOOGLE_CLIENT_SECRET")), |
| 232 | }, |
| 233 | }, |
| 234 | }); |
| 235 | }), |
| 236 | ); |
| 237 | ``` |
| 238 | |
| 239 | `AuthLive` creates better-auth with GitHub and Google. The `Auth` service names the two things the Worker needs from it: its routes and the session behind a request. |
| 240 | |
| 241 | ## Check the session |
| 242 | |
| 243 | ```typescript |
| 244 | // src/Session.ts |
| 245 | import { RuntimeContext } from "alchemy"; |
| 246 | import * as Effect from "effect/Effect"; |
| 247 | import * as Layer from "effect/Layer"; |
| 248 | import { Auth } from "./Auth.ts"; |
| 249 | import { CurrentUser } from "./CurrentUser.context.ts"; |
| 250 | import { Session, Unauthorized } from "./Session.middleware.ts"; |
| 251 | import { UserId } from "./User.id.ts"; |
| 252 | |
| 253 | /** The {@link Session} middleware: the user better-auth signed in, or Unauthorized. */ |
| 254 | export const SessionLive = Layer.effect( |
| 255 | Session, |
| 256 | Effect.gen(function* () { |
| 257 | const auth = yield* Auth; |
| 258 | return (effect, { headers }) => |
| 259 | Effect.gen(function* () { |
| 260 | const session = yield* auth |
| 261 | .getSession(new Headers(Object.entries(headers))) |
| 262 | .pipe(Effect.orDie); |
| 263 | if (session === null) return yield* new Unauthorized(); |
| 264 | return yield* effect.pipe( |
| 265 | Effect.provideService(CurrentUser, { |
| 266 | userId: UserId.make(session.user.id), |
| 267 | name: session.user.name, |
| 268 | }), |
| 269 | ); |
| 270 | }).pipe(Effect.provide(RuntimeContext.phantom)); |
| 271 | }), |
| 272 | ); |
| 273 | ``` |
| 274 | |
| 275 | `SessionLive` asks better-auth for the session behind the request's cookie. No session is `Unauthorized`; a session becomes `CurrentUser`. |
| 276 | |
| 277 | ## Serve the Api from a Worker |
| 278 | |
| 279 | ```typescript |
| 280 | // src/Database.ts |
| 281 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 282 | |
| 283 | /** better-auth's users, accounts and sessions. */ |
| 284 | export const AuthDb = Cloudflare.D1.Database("AuthDb"); |
| 285 | ``` |
| 286 | |
| 287 | ```typescript |
| 288 | // src/NotesWorker.ts |
| 289 | import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; |
| 290 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 291 | import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain"; |
| 292 | import * as Effect from "effect/Effect"; |
| 293 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 294 | import * as Layer from "effect/Layer"; |
| 295 | import { Auth, AuthLive } from "./Auth.ts"; |
| 296 | import { AuthDb } from "./Database.ts"; |
| 297 | import { NotesModel } from "./Notes.model.ts"; |
| 298 | import { NotesApi } from "./NotesApi.api.ts"; |
| 299 | import { SessionLive } from "./Session.ts"; |
| 300 | |
| 301 | const NotesLive = SessionLive.pipe( |
| 302 | Layer.provideMerge(AuthLive), |
| 303 | Layer.provideMerge(NotesModel.layer(Layer.empty)), |
| 304 | Layer.provide(Layer.mergeAll(DomainCloudflare.layerDurableObjects(), CloudflareD1(AuthDb))), |
| 305 | ); |
| 306 | |
| 307 | /** Serves better-auth's routes under /api/auth, and the NotesApi under /api. */ |
| 308 | export default class NotesWorker extends Cloudflare.Worker<NotesWorker>()( |
| 309 | "NotesWorker", |
| 310 | { |
| 311 | main: import.meta.url, |
| 312 | compatibility: { flags: ["nodejs_compat"] }, |
| 313 | }, |
| 314 | Effect.gen(function* () { |
| 315 | const auth = yield* Auth; |
| 316 | const api = yield* NotesApi; |
| 317 | return { |
| 318 | fetch: Effect.gen(function* () { |
| 319 | const request = yield* HttpServerRequest; |
| 320 | const path = new URL(request.url, "http://localhost").pathname; |
| 321 | if (path.startsWith("/api/auth/")) return yield* auth.fetch; |
| 322 | return yield* api.fetch; |
| 323 | }), |
| 324 | }; |
| 325 | }).pipe(Effect.provide(NotesLive)), |
| 326 | ) {} |
| 327 | ``` |
| 328 | |
| 329 | The Notes Worker serves better-auth's routes under `/api/auth` and the NotesApi under `/api`. `CloudflareD1(AuthDb)` keeps users and sessions in D1 and migrates its tables on deploy. |
| 330 | |
| 331 | ## Install foldkit |
| 332 | |
| 333 | ```sh |
| 334 | bun add foldkit @effect/platform-browser |
| 335 | bun add -d vite @foldkit/vite-plugin |
| 336 | ``` |
| 337 | |
| 338 | ## Configure Vite |
| 339 | |
| 340 | ```typescript |
| 341 | // vite.config.ts |
| 342 | import { foldkit } from "@foldkit/vite-plugin"; |
| 343 | import { defineConfig } from "vite"; |
| 344 | |
| 345 | export default defineConfig({ |
| 346 | plugins: [foldkit()], |
| 347 | optimizeDeps: { |
| 348 | entries: ["src/web/entry.ts"], |
| 349 | include: ["effect", "effect/Function", "effect/http", "@effect/platform-browser"], |
| 350 | }, |
| 351 | }); |
| 352 | ``` |
| 353 | |
| 354 | The foldkit plugin builds the app. `include` pre-bundles the Effect modules foldkit imports, so the browser loads one copy of Effect. |
| 355 | |
| 356 | ## Add the page |
| 357 | |
| 358 | ```html |
| 359 | <!-- index.html --> |
| 360 | <!doctype html> |
| 361 | <html lang="en"> |
| 362 | <head> |
| 363 | <meta charset="UTF-8" /> |
| 364 | <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| 365 | <title>Notes</title> |
| 366 | </head> |
| 367 | <body> |
| 368 | <div id="root"></div> |
| 369 | <script type="module" src="/src/web/entry.ts"></script> |
| 370 | </body> |
| 371 | </html> |
| 372 | ``` |
| 373 | |
| 374 | ## Reach better-auth from the browser |
| 375 | |
| 376 | ```typescript |
| 377 | // src/web/auth.ts |
| 378 | import { createAuthClient } from "better-auth/client"; |
| 379 | |
| 380 | /** better-auth's browser client, on the app's own origin. */ |
| 381 | export const auth = createAuthClient(); |
| 382 | ``` |
| 383 | |
| 384 | ## Write the app |
| 385 | |
| 386 | ```typescript |
| 387 | // src/web/Notes.ts |
| 388 | import type * as Domain from "@alchemy.run/domain"; |
| 389 | import * as Effect from "effect/Effect"; |
| 390 | import * as Schema from "effect/Schema"; |
| 391 | import * as Stream from "effect/Stream"; |
| 392 | import { Command, Subscription, type Update } from "foldkit"; |
| 393 | import type { Document, HtmlBuilder } from "foldkit/html"; |
| 394 | import { defineMessageUnion } from "foldkit/message"; |
| 395 | import { NotesApi } from "../NotesApi.api.ts"; |
| 396 | import { UserId } from "../User.id.ts"; |
| 397 | import { auth } from "./auth.ts"; |
| 398 | |
| 399 | // The services the app's commands and subscriptions use: the NotesApi client. |
| 400 | type Notes = Domain.Api.ClientKey<"NotesApi">; |
| 401 | |
| 402 | const User = Schema.Struct({ userId: UserId, name: Schema.String }); |
| 403 | |
| 404 | /** Who better-auth says is signed in when the page loads, or `null`. */ |
| 405 | export const Flags = Schema.Struct({ user: Schema.NullOr(User) }); |
| 406 | export type Flags = typeof Flags.Type; |
| 407 | |
| 408 | export const Model = Schema.Struct({ |
| 409 | user: Schema.NullOr(User), |
| 410 | draft: Schema.String, |
| 411 | notes: Schema.Array(Schema.String), |
| 412 | error: Schema.NullOr(Schema.String), |
| 413 | }); |
| 414 | export type Model = typeof Model.Type; |
| 415 | |
| 416 | const Provider = Schema.Literals(["github", "google"]); |
| 417 | |
| 418 | export const Message = defineMessageUnion({ |
| 419 | ClickedSignIn: { provider: Provider }, |
| 420 | ClickedSignOut: {}, |
| 421 | ChangedDraft: { text: Schema.String }, |
| 422 | SubmittedNote: {}, |
| 423 | Saved: {}, |
| 424 | Failed: { reason: Schema.String }, |
| 425 | GotNotes: { notes: Schema.Array(Schema.String) }, |
| 426 | }); |
| 427 | export type Message = typeof Message.Type; |
| 428 | |
| 429 | /** Send the browser to GitHub or Google; better-auth brings it back to `/` signed in. */ |
| 430 | export const SignIn = Command.define("SignIn", { |
| 431 | args: { provider: Provider }, |
| 432 | messages: [Message.Failed], |
| 433 | execute: ({ provider }) => |
| 434 | Effect.promise(() => auth.signIn.social({ provider, callbackURL: "/" })).pipe( |
| 435 | Effect.map((result) => Message.Failed({ reason: result.error?.message ?? "Redirecting" })), |
| 436 | ), |
| 437 | }); |
| 438 | |
| 439 | /** Clear better-auth's session, then start over signed out. */ |
| 440 | export const SignOut = Command.define("SignOut", { |
| 441 | args: {}, |
| 442 | messages: [Message.Failed], |
| 443 | execute: () => |
| 444 | Effect.promise(() => auth.signOut()).pipe( |
| 445 | Effect.flatMap(() => Effect.sync(() => location.reload())), |
| 446 | Effect.as(Message.Failed({ reason: "Signing out" })), |
| 447 | ), |
| 448 | }); |
| 449 | |
| 450 | /** Write a note in the user's notebook. The session cookie goes with the call. */ |
| 451 | export const WriteNote = Command.define("WriteNote", { |
| 452 | args: { userId: UserId, text: Schema.String }, |
| 453 | messages: [Message.Saved, Message.Failed], |
| 454 | execute: ({ userId, text }) => |
| 455 | Effect.gen(function* () { |
| 456 | const notes = yield* NotesApi.Client; |
| 457 | yield* notes.WriteNote(userId, { text }); |
| 458 | return Message.Saved(); |
| 459 | }).pipe(Effect.catch((error) => Effect.succeed(Message.Failed({ reason: error._tag })))), |
| 460 | }); |
| 461 | |
| 462 | export const update = (model: Model, message: Message): Update.Return<Model, Message, Notes> => |
| 463 | Message.match<Update.Return<Model, Message, Notes>>(message, { |
| 464 | ClickedSignIn: ({ provider }) => ({ model, commands: [SignIn({ provider })] }), |
| 465 | ClickedSignOut: () => ({ model, commands: [SignOut({})] }), |
| 466 | ChangedDraft: ({ text }) => ({ model: { ...model, draft: text } }), |
| 467 | SubmittedNote: () => |
| 468 | model.user === null || model.draft.trim() === "" |
| 469 | ? { model } |
| 470 | : { |
| 471 | model: { ...model, draft: "" }, |
| 472 | commands: [WriteNote({ userId: model.user.userId, text: model.draft })], |
| 473 | }, |
| 474 | // The note arrives through the subscription; success only clears an error. |
| 475 | Saved: () => ({ model: { ...model, error: null } }), |
| 476 | Failed: ({ reason }) => ({ model: { ...model, error: reason } }), |
| 477 | GotNotes: ({ notes }) => ({ model: { ...model, notes } }), |
| 478 | }); |
| 479 | |
| 480 | export const init = (flags: Flags): Update.Return<Model, Message, Notes> => ({ |
| 481 | model: { user: flags.user, draft: "", notes: [], error: null }, |
| 482 | }); |
| 483 | |
| 484 | export const subscriptions = Subscription.make<Model, Message, Notes>()((entry) => ({ |
| 485 | notes: entry( |
| 486 | { userId: Schema.NullOr(UserId) }, |
| 487 | { |
| 488 | modelToDependencies: (model) => ({ userId: model.user?.userId ?? null }), |
| 489 | dependenciesToStream: ({ userId }) => |
| 490 | userId === null |
| 491 | ? Stream.empty |
| 492 | : Stream.unwrap( |
| 493 | Effect.gen(function* () { |
| 494 | const notes = yield* NotesApi.Client; |
| 495 | return notes.Notes.watch(userId); |
| 496 | }), |
| 497 | ).pipe( |
| 498 | Stream.map(({ state }) => Message.GotNotes({ notes: state?.notes ?? [] })), |
| 499 | Stream.catch((error) => Stream.succeed(Message.Failed({ reason: error._tag }))), |
| 500 | ), |
| 501 | }, |
| 502 | ), |
| 503 | })); |
| 504 | |
| 505 | export const view = (model: Model, h: HtmlBuilder<Message>): Document => ({ |
| 506 | title: "Notes", |
| 507 | body: |
| 508 | model.user === null |
| 509 | ? h.div( |
| 510 | [], |
| 511 | [ |
| 512 | h.h1([], ["Notes"]), |
| 513 | h.button( |
| 514 | [h.OnClick(Message.ClickedSignIn({ provider: "github" }))], |
| 515 | ["Sign in with GitHub"], |
| 516 | ), |
| 517 | h.button( |
| 518 | [h.OnClick(Message.ClickedSignIn({ provider: "google" }))], |
| 519 | ["Sign in with Google"], |
| 520 | ), |
| 521 | h.p([], [model.error ?? ""]), |
| 522 | ], |
| 523 | ) |
| 524 | : h.div( |
| 525 | [], |
| 526 | [ |
| 527 | h.h1([], ["Notes"]), |
| 528 | h.p([], [`Signed in as ${model.user.name}`]), |
| 529 | h.form( |
| 530 | [h.OnSubmit(Message.SubmittedNote())], |
| 531 | [ |
| 532 | h.input([ |
| 533 | h.Value(model.draft), |
| 534 | h.Placeholder("Write a note"), |
| 535 | h.OnInput((text) => Message.ChangedDraft({ text })), |
| 536 | ]), |
| 537 | h.button([h.Type("submit")], ["Save"]), |
| 538 | ], |
| 539 | ), |
| 540 | h.ul( |
| 541 | [], |
| 542 | model.notes.map((note) => h.li([], [note])), |
| 543 | ), |
| 544 | h.button([h.OnClick(Message.ClickedSignOut())], ["Sign out"]), |
| 545 | h.p([], [model.error ?? ""]), |
| 546 | ], |
| 547 | ), |
| 548 | }); |
| 549 | ``` |
| 550 | |
| 551 | `SignIn` hands the browser to better-auth, which sends it to GitHub or Google and back to `/` signed in. `WriteNote` sends the domain command with the session cookie. The notes never change on a command's success: the subscription watches the `Notes` view, so a new note arrives from the watch, including notes written on another device. See [Integrate with foldkit](/domain/foldkit) for how commands, subscriptions and the client fit together. |
| 552 | |
| 553 | ## Start the app |
| 554 | |
| 555 | ```typescript |
| 556 | // src/web/entry.ts |
| 557 | import * as Domain from "@alchemy.run/domain"; |
| 558 | import * as Effect from "effect/Effect"; |
| 559 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 560 | import * as Layer from "effect/Layer"; |
| 561 | import * as Socket from "effect/socket/Socket"; |
| 562 | import { Runtime } from "foldkit"; |
| 563 | import { NotesApi } from "../NotesApi.api.ts"; |
| 564 | import { UserId } from "../User.id.ts"; |
| 565 | import { auth } from "./auth.ts"; |
| 566 | import { Flags, init, Model, subscriptions, update, view } from "./Notes.ts"; |
| 567 | |
| 568 | // Who better-auth says is signed in, before the app starts. |
| 569 | const flags = Effect.promise(() => auth.getSession()).pipe( |
| 570 | Effect.map(({ data }) => ({ |
| 571 | user: data ? { userId: UserId.make(data.user.id), name: data.user.name } : null, |
| 572 | })), |
| 573 | ); |
| 574 | |
| 575 | // The session cookie is first-party, so every call and watch on /api carries it. |
| 576 | const NotesConnection = NotesApi.layerClient.pipe( |
| 577 | Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), |
| 578 | Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Socket.layerWebSocketConstructorGlobal)), |
| 579 | ); |
| 580 | |
| 581 | Runtime.run( |
| 582 | Runtime.makeApplication({ |
| 583 | Model, |
| 584 | Flags, |
| 585 | init, |
| 586 | update, |
| 587 | view, |
| 588 | subscriptions, |
| 589 | resources: NotesConnection, |
| 590 | container: document.getElementById("root"), |
| 591 | }), |
| 592 | { flags }, |
| 593 | ); |
| 594 | ``` |
| 595 | |
| 596 | The app asks better-auth who is signed in before it starts, and connects to the NotesApi on its own origin. `Domain.protocolWebSocket` sends commands over HTTP and opens a WebSocket for each watch; the browser sends the session cookie with both. |
| 597 | |
| 598 | ## Serve the app and the Api from one origin |
| 599 | |
| 600 | ```typescript |
| 601 | // src/web/worker.ts |
| 602 | interface Fetcher { |
| 603 | fetch(request: Request): Promise<Response>; |
| 604 | } |
| 605 | |
| 606 | /** |
| 607 | * The app's Worker: the foldkit build, plus `/api` (better-auth's routes and |
| 608 | * the NotesApi) forwarded to the Notes Worker. One origin for both, so the |
| 609 | * session cookie is first-party and reaches every call and watch. |
| 610 | */ |
| 611 | export default { |
| 612 | fetch(request: Request, env: { readonly ASSETS: Fetcher; readonly NOTES: Fetcher }) { |
| 613 | const { pathname } = new URL(request.url); |
| 614 | return pathname.startsWith("/api") ? env.NOTES.fetch(request) : env.ASSETS.fetch(request); |
| 615 | }, |
| 616 | }; |
| 617 | ``` |
| 618 | |
| 619 | The app's Worker serves the built page and forwards `/api` to the Notes Worker. One origin keeps better-auth's session cookie first-party, so it reaches every call and watch, and GitHub and Google send users back to the app's own URL. |
| 620 | |
| 621 | ## Declare the stack |
| 622 | |
| 623 | ```typescript |
| 624 | // alchemy.run.ts |
| 625 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 626 | import * as Alchemy from "alchemy"; |
| 627 | import * as Effect from "effect/Effect"; |
| 628 | import NotesWorker from "./src/NotesWorker.ts"; |
| 629 | |
| 630 | export default Alchemy.Stack( |
| 631 | "DomainBetterAuth", |
| 632 | { providers: Cloudflare.providers(), state: Cloudflare.state() }, |
| 633 | Effect.gen(function* () { |
| 634 | const notes = yield* NotesWorker; |
| 635 | // The foldkit app, built with Vite. Its Worker serves the build and |
| 636 | // forwards /api to the Notes Worker, so the app and the Api share one origin. |
| 637 | const app = yield* Cloudflare.Website.Foldkit("NotesApp", { |
| 638 | main: "src/web/worker.ts", |
| 639 | env: { NOTES: notes }, |
| 640 | assets: { runWorkerFirst: ["/api", "/api/*"] }, |
| 641 | }); |
| 642 | return { url: app.url.as<string>() }; |
| 643 | }), |
| 644 | ); |
| 645 | ``` |
| 646 | |
| 647 | `Cloudflare.Website.Foldkit` builds the app with Vite and deploys its Worker. `runWorkerFirst` sends `/api` through the Worker instead of the static files. |
| 648 | |
| 649 | ## Register a GitHub OAuth App |
| 650 | |
| 651 | ```text |
| 652 | http://localhost:1338/api/auth/callback/github |
| 653 | ``` |
| 654 | |
| 655 | `alchemy dev` serves the app at the URL it prints, `http://localhost:1338` here. In GitHub **Settings → Developer settings → OAuth Apps → New OAuth App**, set the **Authorization callback URL** to that URL plus `/api/auth/callback/github`. [Sign in with GitHub](/better-auth/sign-in-providers/github#register-the-oauth-app) covers the form. |
| 656 | |
| 657 | ## Register a Google client |
| 658 | |
| 659 | ```text |
| 660 | http://localhost:1338/api/auth/callback/google |
| 661 | ``` |
| 662 | |
| 663 | In the Google Cloud console, create a **Web application** client under **Google Auth platform → Clients** with the app's URL plus `/api/auth/callback/google` as its redirect URI. [Sign in with Google](/better-auth/sign-in-providers/google#name-the-app-on-the-consent-screen) covers the consent screen and client. |
| 664 | |
| 665 | ## Save the credentials |
| 666 | |
| 667 | ```dotenv |
| 668 | # .env |
| 669 | GITHUB_CLIENT_ID=your-github-client-id |
| 670 | GITHUB_CLIENT_SECRET=your-github-client-secret |
| 671 | GOOGLE_CLIENT_ID=your-google-client-id |
| 672 | GOOGLE_CLIENT_SECRET=your-google-client-secret |
| 673 | ``` |
| 674 | |
| 675 | Keep `.env` out of source control. For production, register the deployed app's callback URLs too. |
| 676 | |
| 677 | ## Run it |
| 678 | |
| 679 | ```sh |
| 680 | bun alchemy dev |
| 681 | ``` |
| 682 | |
| 683 | Open the app's URL, sign in with GitHub or Google, and write a note. |
| 684 | |
| 685 | ## Test the app |
| 686 | |
| 687 | ```typescript |
| 688 | // test/Notes.app.test.ts |
| 689 | import { expect, test } from "@effect/vitest"; |
| 690 | import * as Story from "foldkit/story"; |
| 691 | import { UserId } from "../src/User.id.ts"; |
| 692 | import { Message, type Model, SignIn, update, WriteNote } from "../src/web/Notes.ts"; |
| 693 | |
| 694 | const signedOut: Model = { user: null, draft: "", notes: [], error: null }; |
| 695 | const sam: Model = { |
| 696 | user: { userId: UserId.make("u-sam"), name: "Sam" }, |
| 697 | draft: "", |
| 698 | notes: [], |
| 699 | error: null, |
| 700 | }; |
| 701 | |
| 702 | test("signing in sends the browser to the chosen provider", () => |
| 703 | Story.story( |
| 704 | update, |
| 705 | Story.given(signedOut), |
| 706 | Story.message(Message.ClickedSignIn({ provider: "github" })), |
| 707 | Story.Command.resolve(SignIn, Message.Failed({ reason: "Redirecting" })), |
| 708 | Story.model((next) => expect(next.user).toBeNull()), |
| 709 | )); |
| 710 | |
| 711 | test("a note is written to the user's notebook, and arrives from the watch", () => |
| 712 | Story.story( |
| 713 | update, |
| 714 | Story.given(sam), |
| 715 | Story.message(Message.ChangedDraft({ text: "buy milk" })), |
| 716 | Story.message(Message.SubmittedNote()), |
| 717 | Story.Command.resolve(WriteNote, Message.Saved()), |
| 718 | Story.model((next) => { |
| 719 | expect(next.draft).toBe(""); |
| 720 | expect(next.notes).toEqual([]); |
| 721 | }), |
| 722 | Story.message(Message.GotNotes({ notes: ["buy milk"] })), |
| 723 | Story.model((next) => expect(next.notes).toEqual(["buy milk"])), |
| 724 | )); |
| 725 | ``` |
| 726 | |
| 727 | foldkit stories test `update` without a browser or server: each command resolves with the message it would produce. |
| 728 | |
| 729 | ## Test sign-in |
| 730 | |
| 731 | A test can't sign in to GitHub or Google, so the example's test runs a local OpenID Connect provider with [`oauth2-mock-server`](https://www.npmjs.com/package/oauth2-mock-server) and adds it to better-auth with its `genericOAuth` plugin. The test signs users in through the real redirect, callback and session cookie, then calls the NotesApi over HTTP: a user reads their own notes, no session is `Unauthorized`, and someone else's notebook is `NotYours`. See [`test/SignIn.test.ts`](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain-better-auth/test/SignIn.test.ts). |
| 732 | |
| 733 | :::note |
| 734 | For other middleware, such as a second factor, see [Sessions and middleware](/domain/sessions). |
| 735 | ::: |