# Complete Job Search Guide Source: https://tmbv.me/page/career/search-and-outreach Stop guessing your way through applications. This step-by-step system turns your job search into a focused, high-impact campaign. ## The Stack You'll be using the following tools to help you land your next interview: * [Advanced Job Search](https://go.tmbv.me/ajs) - A powerful job search tool that helps us find the exact job that we're looking for. * [Application Autofill](https://chromewebstore.google.com/detail/simplify-copilot-autofill/pbanhockgagggenencehbnadejlgchfc) - A great Chrome extension that'll help us fill out job applications with a single click. * [Finding Outreach Contacts](https://www.linkedin.com/search/results/people/?currentCompany=%5B%2250076%22%5D\&geoUrn=%5B%22103644278%22%5D\&origin=GLOBAL_SEARCH_HEADER\&profileLanguage=%5B%22en%22%5D\&sid=2%2CH\&titleFreeText=talent) - Using LinkedIn's advanced search, you can easily find people who work at the company that you're applying to. This is a great way to find someone who might help you get in touch with the hiring manager or the recruiter for that role. * [Outreach Templating](https://go.tmbv.me/app-outreach) - Effortlessly create personalized connection notes or InMails for any LinkedIn contact with our outreach templating tool.

Before we get started, make sure you have the following resources:

Actually find the job you're looking for. Fill out job applications with a single click. Find people at the company to potentially reach out to. Easily create outreach messages for any LinkedIn contact. ## Advanced Job Search The first step to landing an interview is finding the right job. I've built a [powerful job search tool](https://go.tmbv.me/ajs) that helps you find the exact job that you're looking for. You can filter by job title, location, company, and more. Initially limiting your search to the **last 1 to 5 days** can enhance your application's visibility to recruiters. This is because most job boards prioritize applications based on submission date, with the latest submissions appearing at the top of the list. Thus, hiring teams usually follow a **First In, First Out [(FIFO)](https://youtu.be/1WwhfB3Rs14?si=eWBWaKzkFGW2AT7B\&t=159)** approach for **reviewing applications**, meaning the earlier you apply, the better your chances of being seen. This is in contrast to i.e. BIFO (Best In, First Out) when presenting candidates or LIFO (Last In, First Out) for laying off employees 😄. This tool works by **accepting user inputs** like job title or different experience levels a user may want to target or negate. It then **uses these inputs to generate a search query** that can be used to search for jobs on different job boards like LinkedIn, Ashby, Greenhouse, and more. ### Scenario You're a student looking for a summer internship in software engineering. For example, if you click `Open` on the Greenhouse result, you'll be taken to google.com with the following google search query: ``` site:boards.greenhouse.io/* (inurl:"/job/" OR inurl:"/jobs/" OR inurl:"/apply/") intitle:"software engineer" (intitle:"intern" OR intitle:"internship") ``` View the Greenhouse result by clicking [here](https://www.google.com/search?q=site%3Aboards.greenhouse.io%2F*%20inurl%3A%22%2Fjobs%2F%22%20%22Apply%20for%20this%20Job%22%20intitle%3A%22software%20engineer%22%20\(intitle%3A%22intern%22%20OR%20intitle%3A%22internship%22\)%20-%222%20years%22%20-%222%2B%20years%22%20-%223%20years%22%20-%223%2B%20years%22%20-%224%20years%22%20-%224%2B%20years%22%20-%225%20years%22%20-%225%2B%20years%22). ## Autofill Job Application Now from the search result above, let's say you found a job that you're interested in... When you visit the job application page, you can use the [Simplify Autofill](https://chromewebstore.google.com/detail/simplify-copilot-autofill/pbanhockgagggenencehbnadejlgchfc) Chrome extension to fill out the application with a single click. Here, if you click `LET'S DO IT!` on the extension popup, it'll **autofill** the application form with the details you've provided during onboarding. ## Finding Outreach Contacts Skip this section if the **hiring team** exists in the job description. After applying to the job above, you can use [LinkedIn search](https://www.linkedin.com/search/results/people/) to find people who work at the company you're applying to. ### LinkedIn People Search For example, if you're looking for contacts at Neuralink, you can set the following filters: * Type: `People` * Location: `United States` * Current Company: `Neuralink` * Profile Language: `English` * Title Keywords: `recruiter` (or any other relevant title) Here, you can see a list of `recruiters` in `United States` who work at `Neuralink`. ## Reaching Out Finally, you can use [this simple outreach templating tool](https://go.tmbv.me/app-outreach) to create personalized connection notes or InMails for any LinkedIn contact. You can always *customize the output message* to fit your needs. 😄 Let's say you want to reach out to Laura (from the result above). You can use the outreach templating tool to create a personalized message for them. Below, you have two different outreach messages that you can use to reach out to Laura. If the person you're reaching out to works at the company you're applying to, but **isn't the direct hiring manager or recruiter** for the role. If the person you're reaching out to **is the direct hiring manager or recruiter** for the role. Messages are short (and to the point) so they can be used as `connection notes` on LinkedIn or as the body of an InMail. You can copy the message and use it to reach out to Laura on LinkedIn. This is a great way to get in touch with someone who might help you get your application noticed! ## 🎉 Done! # Agent Configs Source: https://tmbv.me/page/development/agent-configs My personal agent configuration files for coding agents.
Codex Artificial Analysis
```toml config.toml theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} #:schema https://developers.openai.com/codex/config-schema.json model = "gpt-6-astra" model_context_window = 1000000 model_auto_compact_token_limit = 700000 model_auto_compact_token_limit_scope = "total" tool_output_token_limit = 8000 project_doc_max_bytes = 65536 model_reasoning_effort = "low" plan_mode_reasoning_effort = "high" # model_verbosity = "low" (for GPT-5x models) model_reasoning_summary = "concise" personality = "pragmatic" default_permissions = ":workspace" approval_policy = "on-request" approvals_reviewer = "auto_review" web_search = "live" [agents] enabled = true max_concurrent_threads_per_session = 6 default_subagent_model = "gpt-5.6-luna" default_subagent_reasoning_effort = "max" [skills] max_context_tokens = 8000 [tools] web_search = { context_size = "medium" } [tui] status_line = [ "model", "used-tokens", "total-input-tokens", "total-output-tokens", "five-hour-limit", "weekly-limit", "context-remaining", "task-progress", "fast-mode" ] ``` # Rules for an AI-legible codebase Source: https://tmbv.me/page/development/feature-first-structure A short operating manual for structuring projects so coding agents can actually help. Coding agents are only as good as the context you hand them. After a year of shipping Next.js apps with Cursor and Claude Code, the structure that keeps producing clean diffs looks nothing like the default `create-next-app` layout. Six rules. Each one earns its place. ### 1. Organize by feature, not by file type A feature is the unit of work an agent reasons about. "Add avatar upload to profile" touches a component, a router, a schema, a hook, a store. If those five files live under five different top-level folders, you spend the first three minutes of every task assembling a context package by hand. Put them together. Stop paying the tax. ### 2. The feature folder becomes the prompt With the left layout, your prompt starts with "find all files related to profile." With the right layout, your prompt starts with `@src/features/profile`. That's the whole argument. ### 3. `components/` is for primitives and chrome only `src/components/ui/` holds shadcn. `src/components/global/` holds the Navbar and Footer. Nothing else goes here. If a component is used by exactly one feature, it lives inside that feature. This rule is the one people break first. Hold the line — the moment you let `ProfileHeader.tsx` slip into `components/`, the pattern starts rotting. ### 4. Shared code has to earn its spot `src/lib/`, `src/hooks/`, the top-level `trpc/` wiring — these are for things used by two or more features. Everything starts inside a feature folder and graduates out only when a second consumer appears. YAGNI, applied to directories. ### 5. Route handlers stay thin `src/app/` stays as lean as Next.js will let it — route files, layouts, maybe a `loading.tsx`. The actual work is imported from `features/*`. Routes become a table of contents; the chapters live elsewhere. ### 6. Deletion should be a one-liner The real test of a good structure: can you kill a feature with `rm -rf src/features/profile` and one search-and-replace for imports? If yes, your boundaries are real. If no, you have leaks to fix. ### Try it on one feature Don't refactor the whole app on a Tuesday afternoon. Pick the feature you touched most this week, carve out `src/features//`, and move its files in. Run the app. Open your agent. Point it at the folder. You'll know within one prompt whether to keep going. # Polar billing with Better Auth Source: https://tmbv.me/page/development/polar-with-better-auth Add per-user Polar checkout and server-side entitlements to a Better Auth app. This how-to adds per-user software as a service (SaaS) subscription billing to a TypeScript Next.js App Router application that already uses [Better Auth](https://better-auth.com/docs/installation). It creates checkout on the server and authorizes paid access from [Polar Customer State](https://polar.sh/docs/integrate/customer-state). The identity invariant is one Better Auth user to one Polar customer. Polar's [`externalId`](https://polar.sh/docs/api-reference/2026-04/customers/create-customer) stores the immutable application user identifier (ID) on that customer. Email is used only for a verified, one-time recovery association when an existing Polar customer has no external ID. Do not apply this model unchanged to organizations, teams, shared accounts, or seat-based billing. The request path has four responsibilities: * **Better Auth**: authenticates the request and proves email ownership before any email-based customer association. * **Your server**: creates or associates the Polar customer and sets the allowed product, discounts, trials, customer IP address, and redirect URLs. * **Polar Customer State**: returns the current customer and granted benefits. * **Your authorization code**: checks one stable benefit ID before protected work runs. The implementation follows this order: 1. Pin the integration and local validation environment. 2. Define the customer lifecycle and recurring product. 3. Validate environment configuration. 4. Add the Polar plugin to the existing Better Auth configuration. 5. Create or safely associate a verified customer's Polar record. 6. Add bounded local rate limits and Customer State caching. 7. Create checkout from a server-owned route. 8. Authorize protected work from Customer State. 9. Resolve checkout completion from verified server state. 10. Add abortable, bounded client polling and portal recovery. 11. Run build and sandbox validation before deployment. ## Use the supported package set The integration examples target exact Better Auth, Polar adapter, and Polar SDK versions. The optional validation harness is a disposable runnable application, not a production database or a replacement for your existing auth setup. For an existing application, keep its current Better Auth installation in place. The snippets on this page were validated with Better Auth `1.6.23`; do not silently replace a working auth version just to follow the billing setup. Install the missing integration dependencies with exact versions: ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npm install --save-exact @polar-sh/better-auth@1.8.4 \ @polar-sh/sdk@0.47.1 zod@4.4.3 npm ls better-auth ``` If `npm ls` reports a Better Auth version other than `1.6.23`, confirm adapter compatibility and run the full validation path before deployment. Skip framework, React, database, and TypeScript replacement when your application already supplies them. For the clean validation harness, use Node.js `22.19.0` with npm `10.9.3`. Next.js 16 requires Node.js 20.9 or newer, and this harness keeps the runtime and Node type declarations on the same major version. Create a TypeScript App Router application with `create-next-app` `16.2.10`. The executable package version is available in the [`create-next-app` registry metadata](https://registry.npmjs.org/create-next-app/16.2.10). ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npx create-next-app@16.2.10 polar-billing-check \ --ts --app --src-dir --use-npm \ --import-alias "@/*" --yes cd polar-billing-check ``` Record the exact local runtime, then make npm save exact dependency versions. ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} printf '22.19.0\n' > .nvmrc npm pkg set engines.node="22.19.0" npm pkg set packageManager="npm@10.9.3" npm config set save-exact true --location=project ``` Install the framework, integration, SQLite, and matching type packages used by the runnable example. ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npm install next@16.2.10 react@19.2.7 react-dom@19.2.7 npm install better-auth@1.6.23 @polar-sh/better-auth@1.8.4 npm install @polar-sh/sdk@0.47.1 better-sqlite3@12.11.1 zod@4.4.3 npm install -D typescript@5.8.3 @types/node@22.19.21 npm install -D @types/react@19.2.17 @types/react-dom@19.2.3 npm install -D @types/better-sqlite3@7.6.13 ``` Adapter `1.8.4` declares `@polar-sh/sdk` `^0.47.0` and Better Auth `^1.4.12` in its pinned [release manifest](https://github.com/polarsource/polar-adapters/blob/cbd4bd5/packages/polar-betterauth/package.json). Keep the SDK on `0.47.x` while using this adapter version. Also keep the canonical [Better Auth Polar plugin documentation](https://better-auth.com/docs/plugins/polar) for supported usage and the pinned source only for version-specific behavior. ## Choose the customer lifecycle before configuring Better Auth This guide uses `createCustomerOnSignUp: false` so signup does not depend on Polar availability. Lazy creation also means the adapter's customer create, profile synchronization, and delete hooks are not your lifecycle policy. With eager creation enabled, adapter `1.8.4` runs customer hooks around Better Auth user operations. Those hooks are best-effort synchronization: they depend on Better Auth operation context, and remote deletion can fail after the local user has already been deleted. See the pinned [customer hooks](https://github.com/polarsource/polar-adapters/blob/cbd4bd5/packages/polar-betterauth/src/hooks/customer.ts). Define these policies before deploying lazy creation: * **Email and name changes**: update the Polar customer by its existing external ID after the local change is verified. Do not reassign ownership by email. * **Account deletion**: decide whether to retain, delete, or anonymize the Polar customer. Deleting a customer can cancel subscriptions and revoke benefits; use the versioned [Delete Customer API](https://polar.sh/docs/api-reference/2026-04/customers/delete-customer) only when that matches your product policy. * **Account recreation**: a new local user ID is a new identity. Do not let a new account take over a Polar customer whose external ID points to the deleted ID. Reconcile the record through an authenticated support or administrative flow. * **Account merge**: choose the surviving local user ID first, then reconcile the Polar customer deliberately. Never infer a merge only from matching email. ## Prepare Polar and the application Create a recurring subscription product for the paid plan, not a one-time purchase. A Feature Flag benefit attached to a recurring product follows the subscription lifecycle, while a one-time purchase can grant the benefit permanently. See [Feature Flag benefits](https://polar.sh/docs/features/benefits/feature-flags). Create the recurring Polar product, then attach one Feature Flag benefit for the application capability this guide calls Pro access. Copy both IDs. Create a Polar [Organization Access Token](https://polar.sh/docs/integrate/authentication) and grant only the scopes used here: * `customers:read` * `customers:write` * `checkouts:read` * `checkouts:write` * `customer_sessions:write` The email recovery association later in this guide is safe only after the application has proved ownership of the session email. Keep signup rate limits, bot controls, and email verification enabled. For email and password, configure `emailVerification.sendVerificationEmail` and `emailAndPassword.requireEmailVerification: true`. For social sign-in, enable the provider-specific `requireEmailVerification` option only for providers that report a trustworthy verification claim. Otherwise, require a separate verified email step before billing. Generate a high-entropy Better Auth secret instead of copying a sample value. For the pinned version in this guide, run: ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npx auth@1.6.23 secret ``` Use one canonical application origin. This guide passes `APP_URL` directly to Better Auth instead of maintaining a second `BETTER_AUTH_URL` value. ```dotenv theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} BETTER_AUTH_SECRET= APP_URL=http://localhost:3000 POLAR_ENVIRONMENT=sandbox POLAR_ACCESS_TOKEN= POLAR_PRO_PRODUCT_ID=12345678-1234-4234-8234-123456789012 POLAR_PRO_BENEFIT_ID=23456789-2345-4345-8345-567890123456 CUSTOMER_IP_HEADER= ``` `CUSTOMER_IP_HEADER` is empty in the local sandbox. In production, set it to the header your trusted ingress overwrites with the connecting customer IP. Do not trust a client-controlled forwarded header. Polar uses the request IP for country, currency, billing-country prefilling, and preliminary tax behavior when checkout is created from a backend. ## Validate configuration at startup Validate configuration once so route code uses typed values. The shared universally unique identifier (UUID) schema also validates checkout IDs later. Production requires HTTPS and a configured trusted customer-IP header. ```typescript {3-13} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/validation.ts import { z } from "zod"; export const uuidSchema = z.string().uuid(); export const billingEnvSchema = z.object({ BETTER_AUTH_SECRET: z.string().min(32), APP_URL: z.string().url(), POLAR_ENVIRONMENT: z.enum(["sandbox", "production"]), POLAR_ACCESS_TOKEN: z.string().min(1), POLAR_PRO_PRODUCT_ID: uuidSchema, POLAR_PRO_BENEFIT_ID: uuidSchema, CUSTOMER_IP_HEADER: z.string().regex(/^[a-z0-9-]*$/), }); ``` Parse the origin and apply production-only requirements explicitly. ```typescript {4-18} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/env.ts import { billingEnvSchema } from "@/lib/validation"; const parsed = billingEnvSchema.parse(process.env); const appUrl = new URL(parsed.APP_URL); if (appUrl.pathname !== "/" || appUrl.search || appUrl.hash) { throw new Error("APP_URL must contain only an origin"); } if (appUrl.username || appUrl.password) { throw new Error("APP_URL cannot contain credentials"); } if (appUrl.protocol !== "http:" && appUrl.protocol !== "https:") { throw new Error("APP_URL must use HTTP or HTTPS"); } if (parsed.POLAR_ENVIRONMENT === "production") { if (appUrl.protocol !== "https:") throw new Error("HTTPS is required"); if (!parsed.CUSTOMER_IP_HEADER) { throw new Error("CUSTOMER_IP_HEADER is required in production"); } } ``` Export normalized values and turn an empty sandbox IP header into `undefined`. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} export const env = Object.freeze({ ...parsed, APP_URL: appUrl.origin, CUSTOMER_IP_HEADER: parsed.CUSTOMER_IP_HEADER || undefined, }); ``` ## Configure Better Auth and Polar Add the Polar plugin to your existing Better Auth configuration without replacing its database adapter, auth methods, session policy, trusted origins, providers, or hooks. The full SQLite configuration below exists only for the clean harness. Create one Polar client for server code. Global retries remain disabled so write requests are never replayed automatically. ```typescript {4-9} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/polar.ts import { Polar } from "@polar-sh/sdk"; import { env } from "@/lib/env"; export const polarClient = new Polar({ accessToken: env.POLAR_ACCESS_TOKEN, server: env.POLAR_ENVIRONMENT, timeoutMs: 3_000, retryConfig: { strategy: "none" }, }); ``` Define the Polar billing plugin separately so an existing app can append the same plugin to its current `plugins` array. ```typescript {5-14} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/auth.ts import { polar, portal } from "@polar-sh/better-auth"; import { env } from "@/lib/env"; import { polarClient } from "@/lib/polar"; import { billingRoutes } from "@/lib/billing/routes"; const polarBilling = polar({ client: polarClient, createCustomerOnSignUp: false, use: [ portal({ returnUrl: new URL(billingRoutes.settings, env.APP_URL).toString(), }), ], }); ``` In your existing application, add `polarBilling` to the existing `plugins` array and keep the rest of your auth configuration unchanged. Also ensure every auth method that can reach billing produces a verified local email before association. The clean harness uses SQLite and logs verification links only in sandbox. Never use this database or console delivery as a production starting point. ```typescript {7-20} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} import Database from "better-sqlite3"; import { betterAuth } from "better-auth"; export const auth = betterAuth({ baseURL: env.APP_URL, secret: env.BETTER_AUTH_SECRET, database: new Database("auth.db"), emailVerification: { sendVerificationEmail: async ({ user, url }) => { if (env.POLAR_ENVIRONMENT === "production") { throw new Error("Configure transactional email before production"); } console.info(`Verify ${user.email}: ${url}`); }, sendOnSignUp: true, sendOnSignIn: true, }, emailAndPassword: { enabled: true, requireEmailVerification: true }, plugins: [polarBilling], }); ``` Mount the Better Auth handler at its documented App Router path. This mount also serves the Polar portal endpoint added by the adapter. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/api/auth/[...all]/route.ts import { toNextJsHandler } from "better-auth/next-js"; import { auth } from "@/lib/auth"; export const { GET, POST } = toNextJsHandler(auth); ``` For the clean harness only, create the SQLite schema with the CLI version that matches the deployed Better Auth version. Do not use a mutable `latest` CLI for a schema migration. ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npx auth@1.6.23 migrate printf '\nauth.db\nauth.db-*\n' >> .gitignore ``` `auth.db` is local-only. A relative SQLite file is not suitable for typical serverless, ephemeral, or multi-process deployment, and it can contain user and session data after testing. Production must keep the application's existing production-grade database configuration. ## Create or associate the customer on the first billing action The first billing action must ensure the verified signed-in user maps to exactly one Polar customer. Email recovery is allowed only when the local email is verified and the matching Polar customer has no external ID. Import the generated SDK error classes from their pinned model paths. These deep imports target SDK `0.47.1`, so re-run validation before changing the SDK. ```typescript {1-12} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/customer.ts import { HTTPValidationError } from "@polar-sh/sdk/models/errors/httpvalidationerror.js"; import { ResourceNotFound } from "@polar-sh/sdk/models/errors/resourcenotfound.js"; import { polarClient } from "@/lib/polar"; export type BillingUser = { id: string; email: string; emailVerified: boolean; name: string; }; ``` Reject unverified identities inside the helper as defense in depth, even though billing routes also reject them before calling this code. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} export class EmailVerificationRequiredError extends Error {} export class PolarCustomerConflictError extends Error {} function assertVerifiedUser(user: BillingUser) { if (!user.emailVerified) { throw new EmailVerificationRequiredError(); } } ``` Associate an email-matched customer only when exactly one match exists and its external ID is empty or already matches the local user. Polar external IDs are unique and should be treated as immutable ownership identifiers. ```typescript {8-20} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} async function associateExistingCustomer(user: BillingUser) { const { result } = await polarClient.customers.list({ email: user.email }); if (result.items.length === 0) return false; if (result.items.length !== 1) { throw new PolarCustomerConflictError("Customer email is not unique"); } const customer = result.items[0]; if (customer.externalId === user.id) return true; if (customer.externalId) { throw new PolarCustomerConflictError("Customer has another owner"); } await polarClient.customers.update({ id: customer.id, customerUpdate: { externalId: user.id }, }); return true; } ``` Create a customer only after the verified email lookup fails. A `422` does not become success by itself: the helper performs one read-after-write recovery lookup and rethrows the original validation error unless that lookup proves the customer is now safely owned by this user. This bounds the concurrency recovery path without treating arbitrary invalid data as a successful create. ```typescript {2-20} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} export async function ensurePolarCustomer(user: BillingUser) { assertVerifiedUser(user); try { await polarClient.customers.getStateExternal({ externalId: user.id }); return; } catch (error) { if (!(error instanceof ResourceNotFound)) throw error; } if (await associateExistingCustomer(user)) return; try { await polarClient.customers.create({ externalId: user.id, email: user.email, name: user.name, }); } catch (error) { if (!(error instanceof HTTPValidationError)) throw error; if (await associateExistingCustomer(user)) return; throw error; } } ``` After initial association, synchronize verified profile changes by external ID in your own account-update flow. Do not use this email recovery helper as a general profile synchronization mechanism. ## Add bounded local API controls The harness uses process-local controls so it can run without another service. Production with multiple processes must replace them with shared implementations. A distributed rate-limit consume/reset operation must be atomic; a remote read-then-write sequence is not sufficient. Use one bounded fixed-window helper for checkout, status polling, and protected feature routes. It removes expired entries during periodic sweeps and returns a retry delay for `Retry-After`. ```typescript {6-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/rate-limit.ts const buckets = new Map(); let nextSweep = 0; export function consumeRateLimit(key: string, max: number, windowMs = 60_000) { const now = Date.now(); if (now >= nextSweep) { for (const [name, value] of buckets) { if (value.resetAt <= now) buckets.delete(name); } nextSweep = now + 60_000; } const current = buckets.get(key); if (!current || current.resetAt <= now) { buckets.set(key, { count: 1, resetAt: now + windowMs }); return { allowed: true, retryAfter: 0 }; } const retryAfter = Math.ceil((current.resetAt - now) / 1_000); if (current.count >= max) return { allowed: false, retryAfter }; current.count += 1; return { allowed: true, retryAfter }; } ``` Customer State is latency-sensitive and authorization-sensitive. This harness uses a three-second per-user cache to reduce repeated Polar calls. That creates up to three seconds of entitlement staleness, so choose a shorter, longer, or zero TTL according to your revocation requirements. ```typescript {8-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/state.ts import type { CustomerState } from "@polar-sh/sdk/models/components/customerstate.js"; import { ResourceNotFound } from "@polar-sh/sdk/models/errors/resourcenotfound.js"; import { polarClient } from "@/lib/polar"; export type BillingState = CustomerState | null; const cache = new Map(); const ttlMs = 3_000; const maxEntries = 1_000; export async function getBillingState(userId: string): Promise { const cached = cache.get(userId); if (cached && cached.expiresAt > Date.now()) return cached.value; let value: BillingState; try { value = await polarClient.customers.getStateExternal({ externalId: userId, }); } catch (error) { if (!(error instanceof ResourceNotFound)) throw error; value = null; } ``` Bound the local cache instead of allowing it to grow with every distinct user. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} cache.delete(userId); cache.set(userId, { value, expiresAt: Date.now() + ttlMs }); while (cache.size > maxEntries) { const oldest = cache.keys().next().value as string | undefined; if (!oldest) break; cache.delete(oldest); } return value; } ``` The SDK timeout, short cache, and per-user route limits bound local latency and API consumption. Higher-volume production systems should use a shared cache, organization-wide budgets, and a circuit breaker so a Polar outage does not turn all application traffic into synchronized upstream calls. ## Create checkout from a server-owned route Keep price-sensitive fields on the server. The browser sends only the plan key; the server sets the product, discount policy, trial policy, customer identity, customer IP address, and redirect URLs. Define application-specific route constants once so examples cannot drift. Replace these values when your application uses different paths. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/routes.ts export const billingRoutes = { signIn: "/sign-in", settings: "/settings/billing", app: "/app", finish: "/billing/finish", } as const; ``` Read the customer IP only from a header guaranteed by your deployment ingress. For comma-separated trusted forwarding headers, this example uses the first address after the trusted proxy has overwritten client input. ```typescript {5-18} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/request.ts import { isIP } from "node:net"; import { env } from "@/lib/env"; export function hasValidOrigin(request: Request) { return request.headers.get("origin") === env.APP_URL; } export function getTrustedCustomerIp(request: Request) { if (!env.CUSTOMER_IP_HEADER) return undefined; const raw = request.headers.get(env.CUSTOMER_IP_HEADER); const value = raw?.split(",")[0]?.trim(); if (!value || isIP(value) === 0) { throw new Error("Trusted customer IP is unavailable"); } return value; } ``` Pass that IP into Polar checkout creation. Polar documents this requirement for backend and Next.js route-handler checkout creation in its [Checkout API guide](https://polar.sh/docs/features/checkout/session). ```typescript {6-19} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/checkout.ts import type { BillingUser } from "@/lib/billing/customer"; import { ensurePolarCustomer } from "@/lib/billing/customer"; import { billingRoutes } from "@/lib/billing/routes"; import { env } from "@/lib/env"; import { polarClient } from "@/lib/polar"; export async function createProCheckout( user: BillingUser, customerIpAddress?: string, ) { await ensurePolarCustomer(user); return polarClient.checkouts.create({ products: [env.POLAR_PRO_PRODUCT_ID], externalCustomerId: user.id, customerEmail: user.email, customerName: user.name, customerIpAddress, ``` Finish the checkout policy with server-owned discount, trial, and redirect settings. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} allowDiscountCodes: false, allowTrial: false, successUrl: new URL( `${billingRoutes.finish}?checkout_id={CHECKOUT_ID}`, env.APP_URL, ).toString(), returnUrl: new URL(billingRoutes.settings, env.APP_URL).toString(), }); } ``` Classify durable Polar configuration failures separately from transient upstream failures while keeping public error messages generic. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/polar-errors.ts export function polarErrorKind(error: unknown) { if (!error || typeof error !== "object") return "transient"; const record = error as Record; const raw = record.statusCode ?? record.status; const status = typeof raw === "number" ? raw : undefined; if (status === 401 || status === 403 || status === 422) { return "configuration"; } return "transient"; } ``` The checkout route enforces same-origin POST requests, a verified session, one plan key, and a per-user rate limit before creating checkout. ```typescript {8-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/api/billing/checkout/route.ts import { auth } from "@/lib/auth"; import { createProCheckout } from "@/lib/billing/checkout"; import { consumeRateLimit } from "@/lib/billing/rate-limit"; import { getTrustedCustomerIp, hasValidOrigin } from "@/lib/billing/request"; export async function POST(request: Request) { if (!hasValidOrigin(request)) { return Response.json({ error: "Invalid origin" }, { status: 403 }); } const session = await auth.api.getSession({ headers: request.headers }); if (!session) { return Response.json({ error: "Authentication required" }, { status: 401 }); } if (!session.user.emailVerified) { return Response.json({ error: "Verify your email" }, { status: 403 }); } const body = await request.json().catch(() => null) as | { plan?: unknown } | null; if (body?.plan !== "pro") { return Response.json({ error: "Unknown plan" }, { status: 400 }); } ``` Apply the rate limit and include `Retry-After` when it is exceeded. ```typescript {1-15} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} const limit = consumeRateLimit(`checkout:${session.user.id}`, 5); if (!limit.allowed) { return Response.json( { error: "Too many attempts" }, { status: 429, headers: { "Retry-After": String(limit.retryAfter) }, }, ); } try { const customerIp = getTrustedCustomerIp(request); const checkout = await createProCheckout(session.user, customerIp); return Response.json( { url: checkout.url }, { headers: { "Cache-Control": "no-store" } }, ); ``` Handle ownership conflicts, permanent configuration defects, and transient Polar failures separately in logs and status codes. ```typescript {1-21} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} } catch (error) { const { PolarCustomerConflictError } = await import( "@/lib/billing/customer" ); if (error instanceof PolarCustomerConflictError) { return Response.json( { error: "Billing account conflict" }, { status: 409 }, ); } const { polarErrorKind } = await import("@/lib/billing/polar-errors"); const kind = polarErrorKind(error); console.error("Unable to create Polar checkout", { kind, error }); return Response.json( { error: kind === "configuration" ? "Billing configuration error" : "Billing is unavailable" }, { status: kind === "configuration" ? 500 : 503 }, ); } } ``` The dynamic imports above keep each teaching block short. In application code, normal top-level imports are preferable. Add a client button that always resets its disabled state on non-navigation exits, including network failure and invalid JSON. ```tsx {8-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/components/upgrade-button.tsx "use client"; import { useState } from "react"; export function UpgradeButton() { const [starting, setStarting] = useState(false); const [error, setError] = useState(null); async function startCheckout() { if (starting) return; setStarting(true); setError(null); try { const response = await fetch("/api/billing/checkout", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ plan: "pro" }), }); ``` Validate the response shape before navigation and catch all non-navigation failures. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} const json = await response.json().catch(() => null) as | { url?: unknown; error?: unknown } | null; if (!response.ok || typeof json?.url !== "string") { const message = typeof json?.error === "string" ? json.error : "Unable to start checkout"; throw new Error(message); } window.location.assign(json.url); } catch (cause) { setError(cause instanceof Error ? cause.message : "Checkout failed"); } finally { setStarting(false); } } ``` Render disabled and accessible error states. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} return (
{error ?

{error}

: null}
); } ``` ## Read Customer State and authorize on the server Customer State is the authorization source. Only `ResourceNotFound` from the Customer State request means that no Polar customer exists; validation, timeout, rate-limit, and server failures must propagate as availability failures. Authorize the stable benefit ID attached to the recurring product. ```typescript {5-9} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/access.ts import type { BillingState } from "@/lib/billing/state"; import { env } from "@/lib/env"; export function hasProAccess(state: BillingState) { return state?.grantedBenefits.some( (benefit) => benefit.benefitId === env.POLAR_PRO_BENEFIT_ID, ) ?? false; } ``` A state-changing protected POST route applies the same Origin check as checkout, then rate limits each authenticated user before making a Customer State request. ```typescript {7-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/api/pro-feature/route.ts import { auth } from "@/lib/auth"; import { hasProAccess } from "@/lib/billing/access"; import { consumeRateLimit } from "@/lib/billing/rate-limit"; import { hasValidOrigin } from "@/lib/billing/request"; import { getBillingState } from "@/lib/billing/state"; export async function POST(request: Request) { if (!hasValidOrigin(request)) { return Response.json({ error: "Invalid origin" }, { status: 403 }); } const session = await auth.api.getSession({ headers: request.headers }); if (!session) { return Response.json({ error: "Authentication required" }, { status: 401 }); } const limit = consumeRateLimit(`feature:${session.user.id}`, 60); if (!limit.allowed) { return Response.json( { error: "Too many requests" }, { status: 429, headers: { "Retry-After": String(limit.retryAfter) } }, ); } ``` Fail closed on authorization while distinguishing Polar unavailability from a genuine missing entitlement. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} try { const state = await getBillingState(session.user.id); if (!hasProAccess(state)) { return Response.json({ error: "Pro plan required" }, { status: 403 }); } return Response.json( { ok: true }, { headers: { "Cache-Control": "no-store" } }, ); } catch (error) { console.error("Unable to verify Polar entitlement", error); return Response.json({ error: "Entitlement unavailable" }, { status: 503 }); } } ``` ## Route checkout completion from verified state The success URL never grants access. The server verifies the checkout ID, signed-in user, checkout ownership, checkout status, and Customer State before the browser can proceed. ```mermaid theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} stateDiagram-v2 [*] --> CheckCheckout CheckCheckout --> Resume: open CheckCheckout --> Pending: confirmed CheckCheckout --> Failed: failed or expired CheckCheckout --> CheckBenefit: succeeded CheckBenefit --> Ready: benefit granted CheckBenefit --> Pending: within grace period CheckBenefit --> Support: grace period expired Pending --> CheckCheckout: bounded retry Ready --> App Failed --> BillingSettings ``` Define one client-safe runtime contract instead of duplicating a TypeScript type. There are five distinct response states: `pending`, `ready`, `resume`, `failed`, and `support`. ```typescript {3-18} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/status-contract.ts import { z } from "zod"; export const billingStatusSchema = z.discriminatedUnion("state", [ z.object({ state: z.literal("pending") }), z.object({ state: z.literal("resume"), location: z.string().url(), }), z.object({ state: z.enum(["ready", "failed"]), location: z.string().startsWith("/"), }), z.object({ state: z.literal("support"), message: z.string().min(1), }), ]); export type BillingStatus = z.infer; ``` Resolve ownership before interpreting checkout state. The current versioned Polar reference is [Get Checkout Session](https://polar.sh/docs/api-reference/2026-04/checkouts/get-checkout-session). ```typescript {8-21} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/billing/status.ts import type { BillingStatus } from "@/lib/billing/status-contract"; import { hasProAccess } from "@/lib/billing/access"; import { billingRoutes } from "@/lib/billing/routes"; import { getBillingState } from "@/lib/billing/state"; import { polarClient } from "@/lib/polar"; export class CheckoutOwnershipError extends Error {} const benefitGraceMs = 30_000; export async function resolveBillingStatus( userId: string, checkoutId: string, ): Promise { const checkout = await polarClient.checkouts.get({ id: checkoutId }); if (checkout.externalCustomerId !== userId) { throw new CheckoutOwnershipError(); } ``` Route open, confirmed, failed, and expired checkouts explicitly. `confirmed` only means the customer clicked Pay; it does not prove payment success. ```typescript theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} if (checkout.status === "open") { return { state: "resume", location: checkout.url }; } if (checkout.status === "confirmed") return { state: "pending" }; if (checkout.status === "failed" || checkout.status === "expired") { return { state: "failed", location: billingRoutes.settings }; } ``` A succeeded checkout gets a bounded grace period for Customer State propagation. After the grace period, missing the configured benefit becomes an actionable support/configuration state instead of `pending` forever. ```typescript {2-19} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} if (checkout.status === "succeeded") { const state = await getBillingState(userId); if (hasProAccess(state)) { return { state: "ready", location: billingRoutes.app }; } const changedAt = checkout.modifiedAt ?? checkout.createdAt; const age = Date.now() - Date.parse(String(changedAt)); if (age < benefitGraceMs) return { state: "pending" }; console.error("Succeeded checkout missing expected benefit", { checkoutId, userId, }); return { state: "support", message: "Payment succeeded, but Pro access is not available. Contact support.", }; } return { state: "pending" }; } ``` The status endpoint validates the UUID before Polar, rate limits each user, masks ownership mismatches as `404`, and returns `400` for malformed IDs. ```typescript {8-23} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/api/billing/status/route.ts import { ResourceNotFound } from "@polar-sh/sdk/models/errors/resourcenotfound.js"; import { auth } from "@/lib/auth"; import { consumeRateLimit } from "@/lib/billing/rate-limit"; import { CheckoutOwnershipError, resolveBillingStatus, } from "@/lib/billing/status"; import { uuidSchema } from "@/lib/validation"; export async function GET(request: Request) { const session = await auth.api.getSession({ headers: request.headers }); if (!session) { return Response.json({ error: "Authentication required" }, { status: 401 }); } const limit = consumeRateLimit(`status:${session.user.id}`, 20); if (!limit.allowed) { return Response.json( { error: "Too many status requests" }, { status: 429, headers: { "Retry-After": String(limit.retryAfter) } }, ); } ``` Validate and resolve the request without exposing another user's checkout. ```typescript {1-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} const value = new URL(request.url).searchParams.get("checkout_id"); const parsed = uuidSchema.safeParse(value); if (!parsed.success) { return Response.json({ error: "Invalid checkout ID" }, { status: 400 }); } try { const result = await resolveBillingStatus(session.user.id, parsed.data); return Response.json(result, { headers: { "Cache-Control": "no-store" }, }); } catch (error) { if ( error instanceof ResourceNotFound || error instanceof CheckoutOwnershipError ) { return Response.json({ error: "Checkout not found" }, { status: 404 }); } console.error("Unable to resolve checkout status", error); return Response.json({ error: "Billing is unavailable" }, { status: 503 }); } } ``` ## Add an abortable finishing page The browser polls only while the server returns `pending`. Every attempt has a strict 30-second deadline, each fetch has an abort signal, cleanup cancels the active loop, and retry cannot start a second concurrent loop. The server component passes the checkout ID to the client component. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/billing/finish/page.tsx import { FinishingBilling } from "@/components/finishing-billing"; export default async function BillingFinishPage({ searchParams }: { searchParams: Promise<{ checkout_id?: string }>; }) { const { checkout_id: checkoutId } = await searchParams; return ; } ``` Use one abortable delay helper. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/components/finishing-billing.tsx "use client"; import { useEffect, useState } from "react"; import { billingRoutes } from "@/lib/billing/routes"; import { billingStatusSchema } from "@/lib/billing/status-contract"; function abortableSleep(ms: number, signal: AbortSignal) { return new Promise((resolve, reject) => { const onAbort = () => { clearTimeout(timer); reject(new DOMException("Aborted", "AbortError")); }; const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms); signal.addEventListener("abort", onAbort, { once: true }); }); } ``` Poll with bounded exponential backoff. The remaining deadline limits both the fetch timeout and the final sleep, so the attempt does not run beyond 30 seconds. ```tsx {3-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} async function pollBillingStatus(checkoutId: string, signal: AbortSignal) { const deadline = Date.now() + 30_000; let delay = 500; while (Date.now() < deadline) { const remaining = deadline - Date.now(); const requestSignal = AbortSignal.any([ signal, AbortSignal.timeout(Math.min(3_000, remaining)), ]); const query = new URLSearchParams({ checkout_id: checkoutId }); const response = await fetch(`/api/billing/status?${query}`, { credentials: "same-origin", cache: "no-store", signal: requestSignal, }); if (response.ok) { const json = await response.json().catch(() => null); const parsed = billingStatusSchema.safeParse(json); if (!parsed.success) throw new Error("Invalid billing response"); if (parsed.data.state !== "pending") return parsed.data; } else if (response.status !== 503) { throw new Error("Checkout verification failed"); } ``` Bound the delay by the remaining deadline. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} const remainingAfterFetch = deadline - Date.now(); if (remainingAfterFetch <= 0) break; await abortableSleep(Math.min(delay, remainingAfterFetch), signal); delay = Math.min(delay * 2, 5_000); } return null; } ``` Each effect owns one `AbortController`. Cleanup cancels the request and any sleep, including React development Strict Mode cleanup. The retry button is disabled while an attempt is active. ```tsx {5-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} export function FinishingBilling({ checkoutId }: { checkoutId: string }) { const [attempt, setAttempt] = useState(0); const [polling, setPolling] = useState(true); const [message, setMessage] = useState("Verifying payment…"); useEffect(() => { const controller = new AbortController(); setPolling(true); setMessage("Verifying payment…"); void pollBillingStatus(checkoutId, controller.signal) .then((result) => { if (controller.signal.aborted) return; if (!result) { setMessage("Payment is taking longer than expected."); } else if (result.state === "support") { setMessage(result.message); } else { window.location.assign(result.location); } }) ``` Ignore expected aborts, surface other failures, and reset the polling state only for the currently active attempt. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} .catch((error) => { if (controller.signal.aborted) return; console.error("Checkout polling failed", error); setMessage( "Checkout verification failed. Try again or return to billing.", ); }) .finally(() => { if (!controller.signal.aborted) setPolling(false); }); return () => controller.abort(); }, [attempt, checkoutId]); function retry() { setMessage("Verifying payment…"); setPolling(true); setAttempt((value) => value + 1); } ``` Render a finite recovery path. Clicking retry resets the message before starting the next, non-overlapping attempt. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} return (

{message}

Back to billing
); } ``` ## Add the customer portal and runnable harness pages The Polar portal should be offered only after Customer State proves a Polar customer exists. The client must also surface portal failures instead of discarding them. Create the Better Auth client once for sign-in, signup, and Polar portal methods. ```typescript {4-8} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/lib/auth-client.ts import { polarClient } from "@polar-sh/better-auth/client"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ plugins: [polarClient()], }); ``` Handle portal loading and errors in the client component. ```tsx {5-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/components/manage-billing-button.tsx "use client"; import { useState } from "react"; import { authClient } from "@/lib/auth-client"; export function ManageBillingButton() { const [opening, setOpening] = useState(false); const [error, setError] = useState(null); async function openPortal() { setOpening(true); setError(null); try { const result = await authClient.customer.portal(); if (result.error) { setError(result.error.message ?? "Unable to open billing portal"); } } catch { setError("Unable to open billing portal"); } finally { setOpening(false); } } ``` Render the disabled state and an accessible portal error. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} return (
{error ?

{error}

: null}
); } ``` The billing settings page renders Upgrade for users without Pro access and hides Manage billing until a Polar customer exists. ```tsx {8-22} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/settings/billing/page.tsx import { headers } from "next/headers"; import { redirect } from "next/navigation"; import { UpgradeButton } from "@/components/upgrade-button"; import { ManageBillingButton } from "@/components/manage-billing-button"; import { auth } from "@/lib/auth"; import { hasProAccess } from "@/lib/billing/access"; import { billingRoutes } from "@/lib/billing/routes"; import { getBillingState } from "@/lib/billing/state"; export default async function BillingSettingsPage() { const session = await auth.api.getSession({ headers: await headers() }); if (!session) redirect(billingRoutes.signIn); const state = await getBillingState(session.user.id); const pro = hasProAccess(state); return (

Billing

{!pro ? :

Pro access is active.

} {state ? : null}
); } ``` The protected application page checks Customer State server-side rather than trusting the checkout redirect. ```tsx {7-18} theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/app/page.tsx import { headers } from "next/headers"; import { redirect } from "next/navigation"; import { auth } from "@/lib/auth"; import { hasProAccess } from "@/lib/billing/access"; import { billingRoutes } from "@/lib/billing/routes"; import { getBillingState } from "@/lib/billing/state"; export default async function AppPage() { const session = await auth.api.getSession({ headers: await headers() }); if (!session) redirect(billingRoutes.signIn); const state = await getBillingState(session.user.id); if (!hasProAccess(state)) redirect(billingRoutes.settings); return

Pro application

; } ``` For the clean harness, add minimal signup and sign-in controls so the validation path is runnable. The sandbox auth configuration prints verification links to the server console; production must use a transactional email provider. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/components/sign-up-form.tsx "use client"; import { useState } from "react"; import type { FormEvent } from "react"; import { authClient } from "@/lib/auth-client"; export function SignUpForm() { const [message, setMessage] = useState(""); async function submit(event: FormEvent) { event.preventDefault(); const data = new FormData(event.currentTarget); const result = await authClient.signUp.email({ name: String(data.get("name")), email: String(data.get("email")), password: String(data.get("password")), }); setMessage( result.error ? result.error.message : "Check your email to verify.", ); } ``` Render the signup fields. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} return (

Create account

{message}

); } ``` Add a sign-in form that redirects only after Better Auth returns a session. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/components/sign-in-form.tsx "use client"; import { useState } from "react"; import type { FormEvent } from "react"; import { authClient } from "@/lib/auth-client"; import { billingRoutes } from "@/lib/billing/routes"; export function SignInForm() { const [error, setError] = useState(""); async function submit(event: FormEvent) { event.preventDefault(); const data = new FormData(event.currentTarget); const result = await authClient.signIn.email({ email: String(data.get("email")), password: String(data.get("password")), }); if (result.error) setError(result.error.message ?? "Unable to sign in"); else window.location.assign(billingRoutes.settings); } ``` Render the sign-in fields. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} return (

Sign in

{error ?

{error}

: null}
); } ``` Render both controls from `/sign-in`. ```tsx theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} // src/app/sign-in/page.tsx import { SignInForm } from "@/components/sign-in-form"; import { SignUpForm } from "@/components/sign-up-form"; export default function SignInPage() { return
; } ``` Webhooks are not required for this authorization model because every entitlement decision reads Customer State. Add [Polar webhooks](https://polar.sh/docs/integrate/webhooks/endpoints) when another feature needs asynchronous delivery, analytics, or local denormalized state. ## Validate the integration The clean harness is a runnable integration fixture, not proof that payment and security behavior is correct in your deployment. Run TypeScript checking, a full Next.js build, and sandbox tests that exercise auth, ownership, failure, and cancellation paths. Add a type-check script and run both static checks. ```sh theme={"theme":{"light":"one-light","dark":"one-dark-pro"}} npm pkg set scripts.typecheck="tsc --noEmit" npm run typecheck npm run build ``` Before publishing or deploying, verify this path end to end: * [ ] Use Node.js `22.19.0`, npm `10.9.3`, and the exact dependency versions from a clean lockfile. * [ ] Run the pinned Better Auth migration and confirm `auth.db` remains ignored and local-only. * [ ] Sign up with email/password and confirm no authenticated session can use billing until the email is verified. * [ ] For every enabled social provider, confirm the provider-specific verified email policy before allowing billing association. * [ ] Start checkout and confirm extra browser fields cannot change product, discount, trial, redirect, customer identity, or customer IP policy. * [ ] Confirm checkout receives the trusted customer IP in production-like proxy tests and rejects missing or malformed trusted ingress data. * [ ] Confirm a new billing action creates one Polar customer with the local user ID as `externalId`. * [ ] Confirm a verified email-matched customer with no external ID associates once, while an unverified account cannot claim it. * [ ] Reject a Polar customer whose external ID belongs to another local user. * [ ] Verify local email/name changes use your explicit external-ID sync policy. * [ ] Verify account deletion, recreation, and merge behavior matches the written lifecycle policy and never reclaims ownership by email alone. * [ ] Reject cross-origin POST requests on checkout and every protected state-changing route. * [ ] Return `401` without a valid session, `403` for unverified billing identity, and `429` with `Retry-After` after the documented route limits. * [ ] Confirm shared production rate limits use atomic consume/reset semantics and the production cache/circuit-breaker policy bounds organization API pressure. * [ ] Return `400` for malformed checkout IDs and `404` for missing or another user's checkout. * [ ] Route `open`, `confirmed`, `succeeded`, `failed`, and `expired` checkout states as documented. * [ ] Grant access only when Customer State contains `POLAR_PRO_BENEFIT_ID`. * [ ] After a succeeded checkout, confirm missing benefits change from bounded `pending` to the support/configuration state instead of polling forever. * [ ] Return `503` when Polar cannot make an entitlement decision and distinguish durable `401`, `403`, or `422` upstream configuration failures in server logs. * [ ] Unmount and remount the finishing page under React development Strict Mode and confirm old fetches and sleeps are aborted. * [ ] Confirm Try again is disabled during polling and cannot create overlapping attempts. * [ ] Simulate network failure, fetch abort, proxy HTML, and invalid JSON; confirm checkout and polling controls recover with accessible errors. * [ ] Confirm the finishing attempt stops within 30 seconds, including in-flight fetch and delay time. * [ ] Hide Manage billing before a Polar customer exists and surface portal failures with a retryable client state. * [ ] Run `npm run typecheck` and `npm run build` with every published TypeScript and TSX snippet in place. # Enhance Prompt Source: https://tmbv.me/page/prompts/enhance-prompt Use this prompt to turn your original prompt into a clearer, stronger, self-contained instruction set for AI assistants. # I'm Temur Source: https://tmbv.me/updates A quick tl;dr about me. For AI Agents: [llms.txt](/llms.txt) · [skill.md](/skill.md) * [posts](/page/development/ai-coding-tools-ranked) * building things people actually use * making complex tech feel simple * empowering others through content * AI * automation * making products that help people building an end-to-end platform for job-seekers * React library * Next.js framework * TypeScript language * Tailwind CSS css framework * Shadcn UI ui components * [tRPC](https://trpc.io/) apis * Zod validation * Prisma orm * Cloudflare many things * Vercel many things * Microsoft Clarity user behavior * [Axiom](https://axiom.co/) observability * PostHog product * Vercel Analytics general * Claude Code building * Codex building * [Repomix](https://repomix.com/) context generation * Notion docs + planning * [Dub](https://dub.co/) links management * [ImageKit](https://imagekit.io/) media management * OBS + DaVinci Resolve long-form video * [Cap](https://cap.so/) + [CapCut](https://www.capcut.com/) short-form video * Canva design * Google boolean search * Perplexity ai * Reddit communities * LinkedIn people * Twitter social * GitHub emerging tech * is product-focused * has high autonomy * is technical and user-facing * allows me to be a generalist