How I Would Fix exposed API keys and missing auth in a Vercel AI SDK and OpenAI marketplace MVP Using Launch Ready.
The symptom is usually blunt: the app works, but someone can see an OpenAI key in the browser bundle, in a public repo, or in a deployed preview. At the...
How I Would Fix exposed API keys and missing auth in a Vercel AI SDK and OpenAI marketplace MVP Using Launch Ready
The symptom is usually blunt: the app works, but someone can see an OpenAI key in the browser bundle, in a public repo, or in a deployed preview. At the same time, the marketplace lets anyone hit paid AI endpoints without logging in, which means your bill can spike before you even notice.
The most likely root cause is simple: the MVP was built fast, and security boundaries were skipped. The first thing I would inspect is whether any secret is being referenced in client-side code, then I would check whether every AI route and marketplace action has server-side auth enforcement before any OpenAI call or data write.
Triage in the First Hour
I would treat this like a production incident, not a code cleanup. The goal is to stop exposure first, then fix the architecture without breaking the launch.
1. Check Vercel deployment logs for recent builds and environment variable usage. 2. Review the browser bundle for any `OPENAI_API_KEY`, API tokens, or service credentials. 3. Inspect all client-side files that call the Vercel AI SDK or fetch marketplace APIs. 4. Confirm whether auth exists on:
- AI chat routes
- listing creation
- checkout or purchase flows
- admin screens
- webhook handlers
5. Check OpenAI usage dashboard for unusual spikes over the last 24 hours. 6. Review Vercel function logs for unauthenticated requests and repeated failures. 7. Inspect GitHub history for committed secrets or `.env` files. 8. Rotate any exposed key immediately if there is any chance it was shipped publicly. 9. Review Cloudflare and Vercel access settings for preview deployments and public endpoints. 10. Verify whether rate limiting exists on AI routes and account creation endpoints.
If I saw a real exposure, I would assume compromise until proven otherwise. That means rotate first, investigate second.
## Quick checks I would run locally grep -R "OPENAI_API_KEY\|sk-" . --exclude-dir=node_modules --exclude-dir=.git npm run build 2>&1 | tee build.log
Root Causes
Here are the most common failure points I see in marketplace MVPs built with Vercel AI SDK and OpenAI.
| Likely cause | What it looks like | How I confirm it | |---|---|---| | Secret placed in client code | Key appears in browser devtools or bundled JS | Search built assets and source for `process.env` misuse | | Missing server-side auth | Anonymous users can call AI routes | Hit endpoints without a session and watch them succeed | | Weak route protection | Pages are hidden but APIs are open | Check direct POST requests to `/api/*` routes | | Overexposed env vars | Preview or production env vars copied into frontend scope | Review Vercel env settings and build output | | Unprotected webhooks/admin actions | Anyone can trigger state changes | Inspect handler auth checks and signature verification | | No rate limits or abuse controls | Costs rise from bots or repeated refreshes | Compare request volume to user count in logs |
1. Secret used in client-side code
This happens when someone puts `OPENAI_API_KEY` into a React component or passes it through a public config object. It often ships because local testing works fine.
I confirm it by searching built assets, not just source files. If the key is present in browser code, it is already exposed.
2. Auth only exists at the UI layer
A lot of founders hide buttons behind login screens but forget to protect API routes. That means an attacker can skip the UI entirely and call your backend directly.
I confirm this by sending direct requests to protected endpoints without cookies or tokens. If they still work, auth is missing at the wrong layer.
3. Marketplace actions have no ownership checks
In a marketplace MVP, users should only edit their own listings, messages, purchases, or profiles. Missing authorization lets one user read or modify another user's records.
I confirm this by changing IDs in requests and checking whether access still succeeds.
4. Environment variables are mis-scoped
Sometimes secrets are marked as public by mistake, or copied into `NEXT_PUBLIC_` variables so they are bundled into frontend code. That is a common Next.js and Vercel mistake.
I confirm it by reviewing variable names in Vercel and checking build artifacts for leaked values.
5. Webhooks are unsigned or unverified
If your marketplace uses payment events or automation webhooks, those endpoints must verify signatures before acting on them. Without that check, random requests can create fake orders or change account state.
I confirm it by reviewing each webhook handler for signature validation and replay protection.
The Fix Plan
My approach is to stop exposure first, then rebuild the trust boundary around server-only calls.
1. Rotate every exposed OpenAI key immediately.
- Revoke old keys.
- Create new scoped keys if possible.
- Update only server-side environment variables.
2. Remove all secret material from client code.
- No API keys in React components.
- No secrets in public config objects.
- No direct OpenAI calls from the browser.
3. Move OpenAI calls behind authenticated server routes.
- Use Vercel serverless functions or route handlers.
- Keep the OpenAI key on the server only.
- Have the client call your backend with a session token.
4. Add authentication to every sensitive route.
- Login required for chat generation if it costs money.
- Login required for listing creation and edits.
- Admin-only routes must check role plus session.
5. Add authorization checks on record ownership.
- Verify `userId` matches the record owner before read/write/delete.
- Never trust IDs from query params alone.
- Enforce this at the database query level if possible.
6. Lock down webhooks and background jobs.
- Verify signatures on incoming webhooks.
- Reject unsigned requests.
- Make handlers idempotent so retries do not duplicate actions.
7. Add rate limiting to expensive endpoints.
- Limit anonymous traffic aggressively if any public endpoint remains.
- Cap AI calls per user per minute and per day.
- Block obvious bot patterns at Cloudflare too.
8. Audit logs without leaking secrets.
- Log request IDs, user IDs, route names, status codes, latency.
- Never log full prompts if they may contain private data unless you need redacted tracing.
- Never log API keys, bearer tokens, cookies, or raw payment payloads.
9. Tighten deployment hygiene on Vercel and Cloudflare.
- Separate preview from production env vars.
- Restrict who can deploy production changes.
- Turn on SSL everywhere, redirects to canonical domain, DDoS protection, caching where safe.
10. Deploy behind a small rollback plan.
- Keep one clean release branch ready.
- Test on preview first with real auth flows disabled only where safe.
- Roll forward only after smoke tests pass.
A safe architecture here is boring on purpose: browser -> authenticated backend -> OpenAI -> database -> response back to browser. That extra hop prevents secret leakage and gives you one place to enforce policy.
Regression Tests Before Redeploy
Before I ship anything back to users, I want proof that both security holes are closed and normal behavior still works.
Security checks
- Anonymous request to AI route returns `401` or `403`.
- Logged-out user cannot create listings or edit marketplace data.
- User A cannot access User B's private records by changing an ID.
- OpenAI key does not appear in browser source map output or bundled JS.
- Webhook endpoint rejects invalid signatures with `401`.
- Rate limit returns `429` after threshold is exceeded.
- Secrets do not appear in application logs.
Functional checks
- Logged-in user can still generate AI output successfully through server route.
- Listing creation works end-to-end with valid auth.
- Purchase flow still completes after auth enforcement changes.
- Admin screens remain accessible only to authorized roles.
QA acceptance criteria
- 100 percent of sensitive routes require authentication before business logic runs.
- 100 percent of ownership-based operations verify record-level authorization server-side.
- Zero secrets appear in client bundles after build review.
- p95 latency for AI route stays under 2 seconds excluding model timeouts you already expect from OpenAI network variance; if your app was slower before this fix should not add more than 150 ms overhead from auth checks alone.
- Build passes with no new lint errors on security-sensitive files.
- Smoke test coverage includes login/logout, unauthorized access denial, and one full marketplace transaction path.
I would also do one manual exploratory pass on mobile because founders often miss broken redirect states there first. If login loops happen on iPhone Safari but not desktop Chrome, you have not finished fixing production risk yet.
Prevention
This issue should never come back once basic guardrails exist.
Security guardrails
- Keep all third-party API keys server-side only.
- Use least privilege for every token and service account where possible.
- Rotate secrets on schedule and immediately after any suspected exposure.
- Add dependency scanning so vulnerable packages do not slip into release builds.
- Put auth checks inside shared middleware or helper functions instead of repeating them ad hoc across files.
Code review guardrails
I would reject any PR that:
- imports a secret into client code,
- exposes admin routes without role checks,
- adds a new endpoint without input validation,
- logs tokens or full sensitive payloads,
- ships an expensive route without rate limiting,
- bypasses webhook signature verification.
That sounds strict because it saves money later. One leaked key can burn through ad spend faster than most founders expect.
Monitoring guardrails
Set alerts for:
- sudden OpenAI usage spikes,
- repeated 401/403s on protected routes,
- webhook failures,
- unusual deploy frequency,
- high error rates after release,
- latency jumps above your normal p95 baseline.
If you use Cloudflare plus Vercel correctly, you should also monitor:
- blocked requests,
- bot traffic patterns,
- cache hit rate,
- origin error rates,
- SSL certificate status,
- DNS propagation issues after changes.
UX guardrails
Security failures often show up as bad UX too. If users see confusing permission errors with no explanation, support load goes up fast.
I would add:
- clear login prompts before expensive actions,
- empty states that explain why content is locked,
- friendly error states for expired sessions,
- loading states that prevent duplicate submissions,
- role-based navigation so users do not hit dead ends.
Performance guardrails
Security fixes should not make the app feel heavier than necessary.
Keep an eye on:
- bundle size growth after adding auth libraries,
- unnecessary client hydration,
- slow cold starts in serverless functions,
- expensive database lookups inside every request,
- third-party scripts that delay interaction time.
A good target for this kind of MVP is a Lighthouse score above 85 on core pages after deployment cleanup, while keeping protected API p95 under 500 ms excluding model response time when cached data is involved.
When to Use Launch Ready
Use Launch Ready when you need me to clean up deployment risk fast without turning this into a long consulting project.
This sprint fits best when:
- your MVP already works but should not be public yet,
- you found exposed keys or open endpoints,
- your current deploy process feels fragile,
- you need one clean launch path instead of weeks of back-and-forth,
- you want production safety before spending more on ads or outreach.
What I need from you before starting: 1. Access to Vercel project settings and deployments 2. Access to DNS provider and Cloudflare 3. Repository access 4. A list of all env vars currently used 5. Any known admin accounts 6. A quick note on what must stay live during the fix window
If your product has active users already, I will usually recommend fixing this before adding features again. Shipping more functionality on top of exposed keys just increases blast radius when something breaks later during launch week again anyway - sorry that's messy but true!
Delivery Map
References
1. https://roadmap.sh/cyber-security 2. https://roadmap.sh/api-security-best-practices 3. https://roadmap.sh/code-review-best-practices 4. https://vercel.com/docs/environment-variable-management 5. https://platform.openai.com/docs/guides/production-best-practices
---
Take the next step
If this is a problem in your product right now, here is what to do next:
- [Use the free Cyprian tools](/tools) - estimate cost, score app risk, check launch readiness, or pick the right service sprint.
- [Book a discovery call](/contact) - I will tell you honestly whether you need a sprint or if you can DIY the next step.
*Written by Cyprian Tinashe Aarons - senior full-stack and AI engineer helping founders rescue, launch, automate, and scale AI-built products.*
Cyprian Tinashe Aarons — Senior Full Stack & AI Engineer
Cyprian helps founders rescue, secure, deploy, and automate AI-built apps with production-grade engineering, launch systems, and AI integration.