Back to Blog
AI2026-06-309 min Read

AI-Assisted Web Optimization & Security Audits with Antigravity, Codex, and Claude

A practical guide to combining Antigravity, OpenAI Codex, and Anthropic Claude to systematically optimize web application performance and catch critical security vulnerabilities before they reach production.

Related Solutions

Modern web applications face a dual challenge: delivering exceptional performance while defending against an expanding surface of security vulnerabilities.

Traditionally, these were treated as separate disciplines — performance engineers optimized Core Web Vitals while security teams ran OWASP audits. Today, AI tooling has collapsed that gap.

By combining Antigravity (your AI coding assistant), OpenAI Codex (code generation and analysis), and Anthropic Claude (deep reasoning and security analysis), teams can build a continuous, automated audit workflow that accelerates both performance and security posture simultaneously.

This article covers:

  • Setting up your AI audit workflow
  • Performance optimization with Antigravity
  • Security vulnerability detection with Claude
  • Code generation and patching with Codex
  • Prompt engineering for audits
  • Automating audits in CI/CD
  • Common findings and how to fix them
  • Output validation and human review

Why Combine Multiple AI Models?

Each model has distinct strengths.

No single model dominates every task.

ModelStrength
AntigravityCodebase-aware agent with file editing capabilities
OpenAI CodexCode generation, transformation, and diff creation
ClaudeDeep reasoning, long-context analysis, vulnerability research

Using them together creates a compound capability that outperforms any individual model.

The workflow looks like this:

text
1Codebase
23Antigravity scans and gathers context
45Claude reasons over findings
67Codex generates patches and improvements
89Developer reviews and applies changes

Setting Up Your Audit Workflow

Prerequisites

  • Antigravity CLI installed (agy)
  • Access to Claude via API or claude.ai
  • OpenAI API access for Codex/GPT-4o
  • Your web application codebase

Step 1: Give Antigravity Full Codebase Context

Start by opening your project in Antigravity and providing a clear audit goal.

Example prompt:

text
1Perform a full security and performance audit of this web application.
2Identify:
3- XSS vulnerabilities
4- CSRF exposures
5- Insecure headers
6- Unvalidated inputs
7- N+1 query patterns
8- Oversized bundles
9- Missing rate limiting
10- Authentication weaknesses

Antigravity will traverse your codebase, read relevant files, and build a context map before beginning analysis.


Performance Optimization with Antigravity

Core Web Vitals Audit

Antigravity can analyze your frontend code and identify issues affecting:

  • LCP (Largest Contentful Paint) — heavy images, render-blocking scripts
  • CLS (Cumulative Layout Shift) — missing size attributes, dynamically injected elements
  • INP (Interaction to Next Paint) — long JavaScript tasks, synchronous event handlers

Common findings and fixes:

Unoptimized Images

Antigravity will identify <img> tags missing width, height, or loading="lazy".

Before:

html
1<img src="/hero.jpg" alt="Hero">

After:

html
1<img
2  src="/hero.jpg"
3  alt="Hero"
4  width="1200"
5  height="630"
6  loading="lazy"
7  decoding="async"
8/>

Render-Blocking Scripts

html
1<!-- Bad -->
2<script src="/analytics.js"></script>
3
4<!-- Good -->
5<script src="/analytics.js" defer></script>

Missing Font Display Strategy

css
1@font-face {
2  font-family: 'Inter';
3  src: url('/fonts/inter.woff2') format('woff2');
4  font-display: swap; /* Critical for LCP */
5}

Bundle Analysis

Antigravity can examine your build configuration and identify oversized dependencies.

Prompt:

text
1Analyze my package.json and build output.
2Identify packages contributing the most to bundle size
3and suggest lighter alternatives.

Common recommendations:

PackageAlternativeSize Savings
momentdate-fns~65 KB
lodashlodash-es + tree shaking~45 KB
axiosNative fetch~12 KB
joizod~30 KB

Security Auditing with Claude

Claude's long-context reasoning makes it particularly well-suited for:

  • Understanding complex multi-file attack surfaces
  • Reasoning about authentication flows
  • Identifying indirect injection paths
  • Explaining vulnerability impact in business terms

Effective Claude Prompts for Security Audits

Prompt 1: Authentication Flow Review

text
1Review the following authentication implementation.
2Identify:
31. Session fixation risks
42. Insecure token storage
53. Missing rate limiting on login endpoints
64. JWT validation weaknesses
75. OAuth state parameter handling
8
9[Paste your auth code here]

Prompt 2: API Endpoint Security Scan

text
1Analyze these API route handlers for security issues.
2Check for:
3- Missing authorization checks
4- Input validation gaps
5- SQL injection vectors
6- Insecure direct object references (IDOR)
7- Mass assignment vulnerabilities
8
9[Paste route handlers here]

Prompt 3: Dependency Vulnerability Assessment

text
1Review this package.json for known risky dependency patterns.
2Flag packages with:
3- Known CVEs
4- Excessive permissions
5- Unmaintained status
6- Suspicious supply chain indicators
7
8[Paste package.json here]

Common Security Vulnerabilities and AI-Assisted Fixes

1. Cross-Site Scripting (XSS)

Antigravity scans for dangerous patterns like innerHTML, dangerouslySetInnerHTML, and eval().

Vulnerable:

ts
1element.innerHTML = userInput;

Fixed:

ts
1element.textContent = userInput;

In React with sanitization:

tsx
1import DOMPurify from 'dompurify';
2
3function SafeContent({ html }: { html: string }) {
4  return (
5    <div
6      dangerouslySetInnerHTML={{
7        __html: DOMPurify.sanitize(html),
8      }}
9    />
10  );
11}

2. SQL Injection

Claude identifies raw string interpolation in database queries.

Vulnerable:

ts
1const result = await db.query(
2  `SELECT * FROM users WHERE email = '${email}'`
3);

Fixed (parameterized):

ts
1const result = await db.query(
2  'SELECT * FROM users WHERE email = $1',
3  [email]
4);

With Drizzle ORM (safe by default):

ts
1const user = await db
2  .select()
3  .from(users)
4  .where(eq(users.email, email));

3. Missing Security Headers

Antigravity checks your middleware or server config for missing HTTP security headers.

Recommended headers:

ts
1// SvelteKit hooks.server.ts
2export const handle: Handle = async ({ event, resolve }) => {
3  const response = await resolve(event);
4
5  response.headers.set(
6    'Content-Security-Policy',
7    "default-src 'self'; script-src 'self' 'nonce-{nonce}'"
8  );
9  response.headers.set('X-Frame-Options', 'DENY');
10  response.headers.set('X-Content-Type-Options', 'nosniff');
11  response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
12  response.headers.set(
13    'Permissions-Policy',
14    'camera=(), microphone=(), geolocation=()'
15  );
16
17  return response;
18};

4. Insecure Direct Object References (IDOR)

Claude excels at identifying missing ownership checks across API routes.

Vulnerable:

ts
1export async function GET({ params }) {
2  const document = await db.query.documents.findFirst({
3    where: eq(documents.id, params.id),
4  });
5
6  return json(document);
7}

Fixed (with ownership validation):

ts
1export async function GET({ params, locals }) {
2  const document = await db.query.documents.findFirst({
3    where: and(
4      eq(documents.id, params.id),
5      eq(documents.userId, locals.user.id) // ownership check
6    ),
7  });
8
9  if (!document) {
10    return error(404, 'Not found');
11  }
12
13  return json(document);
14}

5. Rate Limiting on Sensitive Endpoints

ts
1import { Ratelimit } from '@upstash/ratelimit';
2import { Redis } from '@upstash/redis';
3
4const ratelimit = new Ratelimit({
5  redis: Redis.fromEnv(),
6  limiter: Ratelimit.slidingWindow(10, '1 m'),
7});
8
9export async function POST({ request, getClientAddress }) {
10  const ip = getClientAddress();
11  const { success } = await ratelimit.limit(ip);
12
13  if (!success) {
14    return error(429, 'Too many requests');
15  }
16
17  // proceed with login logic
18}

Code Generation and Patching with Codex

Once Claude identifies vulnerabilities and Antigravity maps the affected files, Codex generates precise patches.

Workflow

  1. Antigravity identifies the vulnerable file and line range
  2. Claude explains the vulnerability and proposed fix
  3. Codex generates a clean diff or full replacement

Example Codex prompt:

text
1Generate a secure version of the following API route handler.
2Apply these fixes:
31. Add input validation with Zod
42. Add authorization check using session user
53. Sanitize all string inputs
64. Return appropriate HTTP status codes
7
8Original code:
9[paste code]

Codex output example:

ts
1import { z } from 'zod';
2
3const UpdateProfileSchema = z.object({
4  name: z.string().min(1).max(100).trim(),
5  bio: z.string().max(500).trim().optional(),
6});
7
8export async function PUT({ request, locals }) {
9  if (!locals.user) {
10    return error(401, 'Unauthorized');
11  }
12
13  const body = await request.json();
14  const parsed = UpdateProfileSchema.safeParse(body);
15
16  if (!parsed.success) {
17    return error(400, 'Invalid input');
18  }
19
20  await db
21    .update(profiles)
22    .set(parsed.data)
23    .where(eq(profiles.userId, locals.user.id));
24
25  return json({ success: true });
26}

Automating Audits in CI/CD

You can integrate AI-assisted audits into your pipeline using the Antigravity CLI.

GitHub Actions Example

yaml
1name: AI Security Audit
2
3on:
4  pull_request:
5    branches: [main]
6
7jobs:
8  audit:
9    runs-on: ubuntu-latest
10    steps:
11      - uses: actions/checkout@v4
12
13      - name: Install Antigravity CLI
14        run: npm install -g @antigravity/cli
15
16      - name: Run Security Audit
17        env:
18          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
19          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
20        run: |
21          agy audit --security --performance \
22            --output ./audit-report.md
23
24      - name: Upload Audit Report
25        uses: actions/upload-artifact@v4
26        with:
27          name: security-audit
28          path: audit-report.md

Building an Audit Prompt Library

Reusable prompts dramatically increase audit consistency.

Security Audit Prompts

text
1PROMPT: Input Validation Scan
2================================
3Scan all form handlers, API routes, and server actions.
4For each endpoint, verify:
5- All inputs are validated before processing
6- String inputs are trimmed and length-bounded
7- Numeric inputs are coerced and range-checked
8- File uploads are type and size validated
9- No raw user input is passed to database queries
10Report any missing validation with file and line reference.
text
1PROMPT: Authentication Hardening Review
2========================================
3Review the full authentication system including:
4- Login, registration, password reset flows
5- Session creation and invalidation
6- Token generation and validation
7- OAuth/SSO integration
8- MFA implementation
9
10Flag any:
11- Missing brute-force protection
12- Weak token entropy
13- Insecure session storage
14- Missing logout on all devices
15- Token reuse after password change

Interpreting AI Audit Findings

AI findings require human validation before acting on them.

Finding TypeAction
Critical (RCE, SQLi, Auth bypass)Fix immediately, before merge
High (XSS, IDOR, missing auth)Fix in current sprint
Medium (missing headers, weak validation)Backlog with priority
Low (informational, best practice)Review quarterly
False positiveDocument and suppress

Always verify:

  • Does the vulnerability exist in the actual production path?
  • Is the affected code reachable by unauthenticated users?
  • Does the fix introduce any regressions?

Performance + Security as a Unified Practice

The best teams treat performance and security as interconnected.

Performance TechniqueSecurity Benefit
Reducing bundle sizeFewer third-party attack vectors
Strict CSP headersXSS mitigation
Caching with validationPrevents cache poisoning
Rate limitingPrevents brute force and DDoS
Input validationPrevents injection and overflow
Edge runtime isolationLimits blast radius of exploits

Antigravity lets you address both in a single, conversational workflow.


Real-World Audit Workflow Example

Here is a practical example of a full audit session:

Step 1 — Ask Antigravity to map all API routes and identify which ones lack authentication guards.

Step 2 — Paste unprotected routes into Claude with the IDOR prompt above.

Step 3 — For each vulnerability, ask Codex to generate the fix with Zod validation and ownership checks.

Step 4 — Use Antigravity to apply the generated patches directly to your codebase.

Step 5 — Run your test suite to confirm no regressions.

Step 6 — Commit the patched files with a descriptive message referencing the audit findings.

A typical audit of a mid-sized SvelteKit application takes 2–4 hours with this workflow, compared to 2–3 days manually.


Final Thoughts

AI-assisted security and performance audits are not a replacement for human expertise.

They are a force multiplier.

Antigravity understands your codebase deeply. Claude reasons about complex vulnerabilities with nuance. Codex generates production-quality patches at speed.

Together, they enable a continuous, iterative approach to code quality that was previously only possible at large organizations with dedicated security teams.

The teams adopting these workflows today are shipping more secure, faster applications with smaller teams — and that advantage compounds over time.

Start with a single audit prompt. See what surfaces. Then build the habit.

Connect

Let's build together

Currently accepting new projects for remote full-stack development and architecture.
Phone / WhatsApp+34 627 191 675
LocationCosta Blanca, Spain (Remote Worldwide) · Remote worldwide
Available — Responds in 24h
Message

Prefer a call? Message on WhatsApp