The last article defined Encore’s booking API, folder layout and module interfaces. Now add authentication so every booking starts with a verified customer.

Prerequisites

Google needs to recognize Encore before it can return a customer to the application. Complete this setup before writing login code.

  1. Open Google Auth Platform in the Google Cloud console and select or create Encore’s project.
  2. Configure the app name and contact details under Branding. Choose the audience under Audience; add test users while an external app is in testing.
  3. Open Clients, create an OAuth client and select Web application.
  4. Add the exact authorized redirect URIs: http://localhost:3000/auth/google/callback for local development and https://api.example.com/auth/google/callback for production. Google rejects a callback that does not match a registered URI.
  5. Save the client ID and secret as backend settings, GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. Set GOOGLE_REDIRECT_URI to the matching callback and FRONTEND_ORIGIN to the frontend’s origin. Never put the client secret in browser code or public configuration.
  6. Use http://localhost:5173 for the local frontend. Production needs HTTPS origins under the same site, such as https://app.example.com and https://api.example.com. Unrelated hosting-provider domains will not work with this SameSite=Lax cookie design.

Implement Google sign-in

The frontend sends the browser to Encore’s backend, which redirects it to Google. Google authenticates the customer and returns the browser to Encore with a one-use code. The backend exchanges that code, verifies Google’s ID token and creates Encore’s own session cookie before returning the browser to the frontend. The frontend then reads the session to show the authenticated customer.

State protects the login redirect against forgery; PKCE binds the code exchange to that login attempt. Google tokens and the client secret stay on the backend.

A horizontal sign-in flow: frontend starts login, backend prepares state and PKCE, Google returns a code, backend verifies identity and creates a session, then the frontend reads that session

Frontend: start login, then read the session

The customer clicks the sign-in button, which sends the browser to Encore’s backend. Google sign-in eventually returns the browser to the frontend, which asks the backend whether a session now exists. The UI shows the signed-in customer only after that lookup succeeds.

No frontend Google libraries are needed; the button only navigates to the backend. The backend uses @fastify/oauth2 for state and PKCE, and Google’s official google-auth-library to verify the ID token. Do not mix this redirect flow with a separate Google Identity Services credential-button flow.

Local development uses this frontend/public/config.json. Vite, the frontend development server and build tool introduced in Part 3, copies it into dist; change the origin for production.

{ "apiBaseUrl": "http://localhost:3000" }

frontend/src/auth/signin.ts loads that public API origin once. signIn() starts browser navigation rather than making a background login request. readSession() includes Encore’s cookie, returns the user and CSRF token when signed in, returns null for 401, and throws on other failures so the UI can show an error.

Use this pseudocode as a guide, not as executable TypeScript. Give the sketch and the flow above to AI and ask it to generate the complete file, including configuration loading and error handling.

// Pseudocode: frontend/src/auth/signin.ts
// Fetch /config.json without caching; throw if loading or validation fails.
// Export apiOrigin from the validated apiBaseUrl.
/** Start the backend-managed login through browser navigation. */
export function signIn() {
  // Navigate to apiOrigin + /auth/google.
}
/** Read Encore's user and CSRF token, never a Google token. */
export async function readSession(): Promise<{ user: { id: string }; csrfToken: string } | null> {
  // Fetch apiOrigin + /auth/session with credentials: include and cache: no-store.
  // Return null for 401; throw on other failures; otherwise return session JSON.
}

Render the button from app.tsx. The frontend calls readSession() after Google returns, shows the customer and retains the CSRF token in memory. Show session-loading failures as errors, not as a successful sign-in.

// frontend/src/app.tsx, signed-out UI
import { signIn } from './auth/signin';
/** Gives signed-out customers an entry point into the backend's login flow. */
export function SignInButton() {
  return <button onClick={signIn}>Sign in with Google</button>;
}

Backend: verify Google, then create Encore’s session

The backend redirects the browser to Google, receives the callback and exchanges the one-use authorization code. It verifies Google’s ID token before creating Encore’s encrypted session cookie, then redirects to the configured frontend. Later booking requests use Encore’s session rather than asking Google to authenticate each request.

Install the backend libraries from the repository root. @fastify/secure-session encrypts and authenticates a short-lived cookie; @fastify/sensible supplies HTTP errors; pg supplies the PostgreSQL client.

npm --prefix backend install fastify @fastify/cors @fastify/sensible \
  @fastify/oauth2 @fastify/secure-session google-auth-library pg
npm --prefix backend install -D typescript @types/node @types/pg

google-session.ts owns the login routes and returns the Auth interface defined in Part 3. Keep its settings together so the same configuration controls Google’s callback, the frontend redirect and Encore’s session cookie.

// backend/src/auth/google-session.ts
/** Backend-only settings shared by the login routes and application bootstrap. */
export type AuthConfig = {
  clientId: string;
  clientSecret: string;
  redirectUri: string;
  frontendOrigin: string;
  sessionKey: Buffer;
  production: boolean;
};

registerAuth configures an encrypted one-hour session cookie with HttpOnly and SameSite=Lax. Production also requires Secure and a __Host- cookie name. The login handler stores state and the PKCE verifier in short-lived, browser-bound cookies before redirecting to Google.

The callback must reject invalid state, exchange the code using the PKCE verifier and clear the login-attempt cookies. Use google-auth-library to check the ID token’s signature, issuer, audience and expiry; never create a session on failure. Replace any previous session, save the verified user and a fresh random CSRF token, then redirect only to config.frontendOrigin.

The session handler sends Cache-Control: no-store, returns 401 without a valid session and otherwise returns only the user and CSRF token. The returned Auth implementation reads that session in currentUser() and rejects an unexpected origin or a missing/mismatched token in verifyCsrf().

Give this TypeScript pseudocode, AuthConfig, Part 3’s Auth interface and the rules above to AI. Ask it to generate registerAuth and its three handlers using the installed libraries. Review the generated implementation before wiring it into app.ts in the next article.

/** Pseudocode: backend/src/auth/google-session.ts, authentication wiring. */
export async function registerAuth(app: FastifyInstance, config: AuthConfig): Promise<Auth> {
  // Register the encrypted session cookie with the settings above.
  // Start a browser-bound login attempt with state and PKCE.
  app.get('/auth/google', startGoogleLogin);
  // Validate the callback and identity before replacing Encore's session.
  app.get('/auth/google/callback', finishGoogleLogin);
  // Read the session without caching or exposing Google tokens.
  app.get('/auth/session', readEncoreSession);
  // Return Auth with currentUser and origin + CSRF verification.
}

This Google-only example uses google:<sub> as the application user ID. Google’s sub is stable; an email address is not a suitable account key. Add a local user table when Encore needs profiles or multiple identity providers.

The cookie contains only Encore’s minimal session, not Google tokens. Encryption prevents tampering, not theft. These stateless sessions expire after one hour; immediate per-session revocation would require a server-side session store. Share the encryption key across API replicas and rotate it deliberately.

Encore can now identify and authenticate the customer. The next article saves that customer’s booking reliably, without duplicates.