Use AI to turn this article into your first implementation. Give it the folder structure, interfaces, booking endpoint and checks below, then ask it to fill in the code. We are deliberately not publishing a full application.

Even Linus Torvalds has used AI-assisted coding for a hobby project. You still own the result, so review it and understand every line you ship.

The first decision to give your coding assistant is the API style. Encore starts with REST because predictable HTTP requests around booking resources are enough for most day-to-day APIs, including enterprise applications. GraphQL can be worth the extra machinery when clients need complex, nested queries, but fashion alone does not justify its resolvers, authorization rules and query-cost controls. This article defines the REST contract and module interfaces; the next articles implement identity, storage, packaging and deployment.

Make the REST API predictable

A shared API contract defines request and response shapes, status codes, errors and retry behavior. It keeps the web frontend, backend and future mobile clients consistent, making maintenance easier and enhancements compatible with existing clients.

A timeout does not mean booking failed. Idempotency lets clients retry the same attempt without creating another booking. The client reuses one Idempotency-Key per booking intent; the backend scopes it to the verified user, checks the payload and returns the original result, or 409 for changed payloads. The store adapter must save the key, booking and inventory adjustment atomically, all together or not at all, with a unique user/key rule preventing concurrent duplicates.

Apply these broader REST conventions.

  • Use versioned lowercase plural nouns (/v1/bookings) and HTTP methods (POST/GET) to make operations recognizable.
  • Validate requests at runtime; give actionable 400 errors for malformed fields.
  • Distinguish outcomes with 201 and Location, 400 for invalid input, 401 for missing sessions, 403 for failed CSRF checks, 404 for absent/inaccessible resources, 409 for conflicts and 500 for unexpected failures.
  • Return consistent error JSON like {"error":{"code":"sold_out","message":"No tickets remain","requestId":"..."}}. Keep codes stable and messages human-readable; never expose stack traces, tokens or PII. Log internals privately with that correlation ID. Bound retries to transient failures of idempotent operations, not blind 400/401 or sold-out retries.
  • Check sessions and ownership server-side to prevent access to another customer’s booking.

Design Encore’s booking API

Start with two booking-resource endpoints: create a booking and retrieve its confirmation. Keep Google sign-in routes and the operational health check separate from the versioned booking resources. Every path below belongs to the API origin, not the static frontend.

HTTP methodEndpointWhat it does
POST/v1/bookingsReserves tickets for the signed-in customer. Accepts eventId and quantity, requires an Idempotency-Key and CSRF token, and returns 201 with the booking and its Location.
GET/v1/bookings/{id}Returns a booking owned by the signed-in customer. Returns 404 when the booking does not exist or belongs to someone else.
GET/auth/googleStarts sign-in by redirecting the browser to Google with state and a PKCE challenge.
GET/auth/google/callbackReceives Google’s code and state, verifies the login, creates Encore’s session and redirects to the frontend. Google calls this route through the browser; the frontend does not fetch it.
GET/auth/sessionReturns the current Encore user and CSRF token, or 401 when signed out. The response must not be cached.
GET/healthChecks API and database readiness for local checks and the load balancer. Returns 200 only when the database query succeeds.

The booking form sends {"eventId":"launch-night","quantity":2} to POST /v1/bookings. The backend supplies the owner from the session, commits the inventory change and booking together, then returns a Location such as /v1/bookings/booking-id. The frontend can GET that URL to display the saved confirmation.

Keep this first slice small. Seed launch-night in the database; event discovery, booking changes, cancellation and payments need their own contracts when those features enter the story.

Organize the frontend and backend

Keep one repository with two independently built packages. The React frontend renders the UI; the Fastify backend owns identity, booking rules and PostgreSQL access. Do not put database credentials or Google client secrets in the frontend.

Vite is a frontend development server and build tool. It serves the React app locally and builds static production files into frontend/dist; it does not run the booking API.

encore/                              # One repository, two releasable packages
├── frontend/                        # React UI, served and built with Vite
│   ├── package.json                 # React/Vite scripts and dependencies
│   ├── package-lock.json            # Exact dependency versions
│   ├── public/                      # Files served to the browser
│   │   └── config.json              # Public runtime API origin
│   └── src/                         # React and TypeScript source
│       ├── app.tsx                  # React entry and session lookup
│       ├── api/                     # HTTP request helpers
│       │   └── bookings.ts          # Booking requests
│       ├── auth/                    # Browser login helpers
│       │   └── signin.ts            # Start login and read the session
│       └── features/                # UI grouped by feature
│           └── bookings/            # Booking UI
│               └── BookingForm.tsx  # Booking form
├── compose.yaml                     # Local API and PostgreSQL containers
└── backend/                         # Server-side booking logic
    ├── Dockerfile                   # Build and run the API image
    ├── .dockerignore                # Keep secrets and local builds out of the image
    ├── .env                         # Local private settings, never committed
    ├── package.json                 # Package scripts and dependencies
    ├── package-lock.json            # Exact dependency versions
    └── src/                         # Server source
        ├── server.ts                # Start listening for requests
        ├── app.ts                   # Compose services and routes
        ├── auth/                    # Identity and sessions
        │   ├── ports.ts             # Authentication contracts
        │   └── google-session.ts    # Google SDK calls and session helpers
        └── bookings/                # Booking feature
            ├── ports.ts             # Booking and storage contracts
            ├── service.ts           # Booking rules
            ├── routes.ts            # HTTP handlers
            └── postgres.ts          # PostgreSQL storage

Keep responsibilities narrow. frontend/src/app.tsx handles session state, auth/signin.ts handles login navigation, api/bookings.ts makes HTTP requests and BookingForm.tsx handles user input. public/config.json contains only the public API origin.

The backend’s server.ts reads and validates settings, then starts the listener. app.ts connects implementations to routes. Each feature’s ports.ts defines its contracts; service.ts applies use-case rules, routes.ts handles HTTP and postgres.ts handles SQL. google-session.ts owns Google’s login flow and Encore’s session. These are modules in one process, not microservices.

Define interfaces before implementations

Use small TypeScript interfaces so booking logic depends on capabilities, not a Google SDK or SQL client. ports means module contracts here, not network ports. These interfaces belong to Encore; the libraries do not supply them.

// backend/src/auth/ports.ts
import type { FastifyRequest } from 'fastify';
export type User = { id: string };
/** Lets HTTP handlers use Encore's session without knowing the login provider. */
export interface Auth {
  /** Returns the verified session user, or null when signed out. */
  currentUser(req: FastifyRequest): User | null;
  /** Rejects state-changing requests from an untrusted origin or without the session's CSRF token. */
  verifyCsrf(req: FastifyRequest): void;
}
// backend/src/bookings/ports.ts
import type { User } from '../auth/ports.js';
export type BookingInput = { eventId: string; quantity: number };
export type Booking = BookingInput & { id: string; ownerId: string };
/** Defines booking use cases in terms of a verified customer. */
export interface Bookings {
  /** Creates a booking or returns the result of the same customer's retry. */
  create(input: BookingInput, user: User, key: string): Promise<Booking>;
  /** Finds a confirmation only when the customer owns it. */
  find(id: string, user: User): Promise<Booking | null>;
}
/** Defines storage guarantees independently of the PostgreSQL client. */
export interface BookingStore {
  /** Atomically saves inventory, booking and retry key; rejects changed retry payloads. */
  persist(input: BookingInput, ownerId: string, key: string): Promise<Booking>;
  /** Filters by both booking ID and verified owner ID. */
  findOwned(id: string, ownerId: string): Promise<Booking | null>;
}
export class BookingError extends Error {}

Implement the Bookings interface in service.ts and inject a BookingStore. Derive ownership from the verified user, never from submitted JSON. Inventory and retry checks belong inside the storage transaction because they must survive concurrent requests.

// backend/src/bookings/service.ts
import type { Bookings, BookingStore } from './ports.js';
/** Connects booking use cases to storage using the session's owner ID. */
export function createBookings(store: BookingStore): Bookings {
  return {
    create: (input, user, key) => store.persist(input, user.id, key),
    find: (id, user) => store.findOwned(id, user.id),
  };
}

A test can inject an in-memory store without changing the service. The deployed app injects the PostgreSQL adapter. Promise<Booking> means the result arrives asynchronously; it does not itself make writes atomic.

A horizontal flow from the React frontend through routes and Auth, the Bookings service, the BookingStore adapter, and PostgreSQL; all backend modules share one process

The API design and module boundaries are in place. The next article connects Google sign-in so every booking starts with a verified customer.