01. The Modern SEO Equation: Core Web Vitals
SEO is no longer about stuffing hidden keywords into footer text. Modern search engines evaluate performance, accessibility, and user experience as core ranking signals. If your app is sluggish, your ranking plummets.
The Three Critical Metrics
| Metric | What It Measures | Target | Impact |
|---|---|---|---|
| LCP (Largest Contentful Paint) | When the main content becomes visible | < 2.5s | Slow LCP = users leave before seeing content |
| INP (Interaction to Next Paint) | Responsiveness to user input | < 200ms | High INP = UI feels frozen, users abandon |
| CLS (Cumulative Layout Shift) | Visual stability (elements jumping) | < 0.1 | High CLS = users click wrong buttons, lose trust |
Fixing LCP: The Loading Bottleneck
LCP is almost always caused by one of three things: a slow server, render-blocking resources, or large images.
Tell your AI tool: “Optimize LCP by:
- Adding preload tags for critical fonts and hero images
- Adding preconnect for third-party domains (Google Fonts, API endpoints)
- Setting explicit width and height on hero images to prevent layout shift
- Using fetchpriority=‘high’ on the hero image
- Self-hosting fonts with font-display: swap to avoid render blocking
- Inlining critical CSS for above-the-fold content”
Fixing INP: The Responsiveness Bottleneck
INP measures the delay between a user interaction (click, tap, keypress) and the next visual update. High INP happens when the main thread is blocked by long JavaScript execution.
Tell your AI tool: “Optimize INP by breaking long tasks into smaller chunks. Use scheduler.yield() or setTimeout(0) between batches to let the browser handle user interactions. Process data in batches of 50 items instead of all at once.”
Fixing CLS: The Visual Stability Bottleneck
CLS happens when elements shift after the page loads — usually because images or ads don’t have reserved dimensions.
Tell your AI tool: “Fix CLS by:
- Setting explicit width and height (or aspect-ratio) on all images
- Using skeleton placeholders for dynamic content
- Setting min-height on ad banners and lazy-loaded sections
- Using CSS max-height for accordion-style expanding content”
- Using CSS max-height for accordion-style expanding content”
Testing with Lighthouse
Tell your AI tool: “Run Lighthouse to check performance scores. In CI/CD, fail the build if performance drops below 90, accessibility below 95, or SEO below 95.”
How to test:
- Open Chrome DevTools (F12)
- Go to Lighthouse tab
- Click “Analyze page load”
- Check Performance, Accessibility, and SEO scores
02. Meta Tags: The First Impression
Search engines and social platforms read your meta tags to understand what your page is about. Missing or generic meta tags mean missed clicks.
The Complete Meta Tag Template
Tell your AI tool: “Add complete meta tags to every page:
- Primary SEO: title, description, robots, canonical URL
- Open Graph: type, title, description, image (1200x630px), url, site_name
- Twitter Card: card type, title, description, image, creator handle
- Favicon: SVG icon and apple-touch-icon
Use the page title for og:title and twitter:title. Use a 1200x630px image for social previews.”
OG Image Generation
Social platforms show a preview image when your page is shared. Without one, your link looks incomplete.
Tell your AI tool: “Create an OG image generation endpoint using @vercel/og. Accept a ‘title’ query parameter. Generate a 1200x630px image with dark background, brand accent color, and the title text. Return as PNG.”
Or create a static OG image: Design a 1200x630px image in Figma or Canva with your brand colors and title placeholder. Save as PNG and reference it in your meta tags.
03. Structured Data: Schema.org JSON-LD
Schema.org gives search engines explicit semantic meaning about your content. This unlocks rich snippets — star ratings, FAQ dropdowns, breadcrumb trails — directly in search results.
Article Schema
Tell your AI tool: “Add Article Schema.org structured data to every content page. Include: headline, description, author name, publisher name, datePublished, dateModified, and mainEntityOfPage URL.”
What this does: Helps Google understand your content is an article, enabling rich snippets in search results.
FAQ Schema (Unlocks FAQ Dropdowns in Search)
Tell your AI tool: “Add FAQ Schema.org structured data to pages with frequently asked questions. Each question should have a clear answer in the acceptedAnswer field.”
What this does: Google can display your FAQ directly in search results as expandable dropdowns, increasing click-through rate.
BreadcrumbList Schema
Tell your AI tool: “Add BreadcrumbList Schema.org structured data showing the page hierarchy: Home → Part → Section. This helps Google display breadcrumb navigation in search results.”
04. SQL Injection: The Classic Attack
SQL injection happens when user input is concatenated directly into a database query string, allowing an attacker to manipulate the query logic.
The Vulnerability
Never do this: If you put user input directly into a SQL query string, an attacker can inject malicious SQL code that bypasses authentication or steals data.
The attack: If an attacker submits ' OR '1'='1' -- as their email, the query returns ALL users instead of just one — completely bypassing login.
The Fix: Parameterized Queries
Tell your AI tool: “Use parameterized queries for ALL database operations. Never concatenate user input into SQL strings. Use $1, $2 placeholders for PostgreSQL or ? for MySQL.”
What parameterized queries do: The database treats user input as a literal value, never as executable SQL code. Even if the input contains malicious SQL, it’s just a string to search for — not code to execute.
ORM Safety
Modern ORMs (Prisma, Drizzle, SQLAlchemy) use parameterized queries by default. If you’re using an ORM, you’re already protected.
The rule: Never use raw SQL string concatenation with user input. Always use parameterized queries or an ORM.
05. XSS: Cross-Site Scripting
XSS happens when user-controlled content is rendered as executable HTML/JavaScript in another user’s browser.
The Three Types
| Type | How It Works | Example |
|---|---|---|
| Stored XSS | Malicious script saved to database, served to all users | Comment field saves <script>steal()</script> |
| Reflected XSS | Malicious script in URL, reflected in page response | /search?q=<script>alert(1)</script> |
| DOM XSS | JavaScript reads URL/DOM and writes it unsafely | element.innerHTML = location.hash |
The Defense: Output Encoding
Tell your AI tool: “Sanitize all user input before rendering it as HTML. Use DOMPurify to strip dangerous tags and attributes. On the client side, use textContent instead of innerHTML for user-generated content.”
What to do:
- Server-side: Use DOMPurify.sanitize() before storing user input
- Client-side: Use
element.textContent = userInput(renders as text, not HTML) - If you need HTML: Use
DOMPurify.sanitize(userInput)before setting innerHTML
Content Security Policy (CSP)
CSP is the last line of defense. Even if XSS slips through, CSP blocks the browser from executing unauthorized scripts.
Tell your AI tool: “Add Content Security Policy headers. Allow scripts only from your domain. Block inline scripts. Block frames embedding your site. Report violations to /csp-violations.”
06. Path Traversal & Command Injection
Path Traversal
An attacker manipulates file paths to access files outside your intended directory.
Tell your AI tool: “Validate all file path inputs. Use path.basename() to strip directory traversal characters. Verify the resolved path is still inside the intended directory before serving the file.”
The attack: If a user submits ../../../etc/passwd as a filename, they can read system files outside your uploads directory.
Command Injection
If your app passes user input to a shell command, an attacker can execute arbitrary system commands.
Tell your AI tool: “Never use exec() with user input. Use execFile() with array arguments instead. The array format prevents shell interpretation of special characters.”
The attack: If a user submits image.png; rm -rf / as a filename, the shell executes both commands — the image conversion AND the delete command.
07. Rate Limiting: The Traffic Firewall
Without rate limiting, your API is vulnerable to brute-force attacks, credential stuffing, and DDoS.
Fixed Window Algorithm
Simple but has a burst problem — 100 requests at 11:59:59 + 100 requests at 12:00:00 = 200 requests in 2 seconds.
Tell your AI tool: “Implement fixed window rate limiting using Redis. Track requests per IP in 60-second windows. If count exceeds 100, return 429 with retry-after header. Include X-RateLimit-Limit and X-RateLimit-Remaining headers in responses.”
Sliding Window Log Algorithm
More accurate — tracks individual request timestamps, not just a counter.
Tell your AI tool: “Implement sliding window rate limiting using Redis sorted sets. Track individual request timestamps. Remove expired entries, count current window requests. Return 429 with calculated retry-after time if limit exceeded.”
Token Bucket Algorithm
Allows controlled bursts — a bucket fills with tokens at a steady rate, each request consumes one token.
Tell your AI tool: “Implement token bucket rate limiting using Redis. Maintain a token count per IP that refills at 0.1 tokens per second (max 10). Each request consumes one token. If tokens < 1, return 429. Store bucket state with 120-second expiry.”
Rate Limiting Strategy
| Layer | Limit | Window | Purpose |
|---|---|---|---|
| Global | 1000 req/min per IP | 60s | Prevent DDoS |
| API endpoints | 100 req/min per user | 60s | Prevent abuse |
| Auth endpoints | 5 req/15 min per IP | 15min | Prevent brute-force |
| Write endpoints | 20 req/min per user | 60s | Prevent spam |
08. Security Headers: The Complete Setup
Tell your AI tool: “Add all security headers to every response:
- Content-Security-Policy: restrict scripts to your domain
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- Strict-Transport-Security: max-age=31536000
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: disable camera, microphone, geolocation
- X-DNS-Prefetch-Control: off”
Or use helmet.js: Tell your AI tool to “Add helmet middleware for Express.js” — it sets all security headers automatically.
Security Headers Reference
| Header | What It Blocks | Recommended Value |
|---|---|---|
Content-Security-Policy | XSS, data injection | default-src 'self'; script-src 'self' |
X-Frame-Options | Clickjacking | DENY |
X-Content-Type-Options | MIME sniffing attacks | nosniff |
Strict-Transport-Security | Protocol downgrade attacks | max-age=31536000; includeSubDomains |
Referrer-Policy | Referrer leakage | strict-origin-when-cross-origin |
Permissions-Policy | Feature abuse | camera=(), microphone=() |
X-XSS-Protection | Legacy XSS filter | 0 (CSP replaces this) |
09. API Security Checklist
Authentication & Authorization
□ JWT tokens stored in HttpOnly cookies, NOT localStorage
□ Refresh tokens have short expiry (15 min) + rotation
□ RBAC middleware on every protected endpoint
□ API keys scoped to minimum required permissions
Input Validation
□ All user input validated with Zod/Joi schema
□ Parameterized queries for ALL database operations
□ File uploads validated for type, size, and content
□ Request body size limits enforced
Rate Limiting
□ Global rate limit on all endpoints
□ Stricter limits on auth endpoints (5 req/15min)
□ Write endpoints rate-limited to prevent spam
□ Retry-After headers sent with 429 responses
Security Headers
□ CSP header blocks inline scripts
□ HSTS forces HTTPS
□ X-Frame-Options prevents clickjacking
□ X-Content-Type-Options prevents MIME sniffing
Logging & Monitoring
□ Failed auth attempts logged with IP + timestamp
□ Rate limit violations logged
□ SQL injection attempts detected and alerted
□ Unusual traffic patterns trigger alerts
Key Takeaways
| Concept | Mental Model | Senior Insight |
|---|---|---|
| LCP | When main content appears | Preload critical assets, self-host fonts, use fetchpriority="high" on hero images |
| INP | Input-to-visual delay | Break long tasks with scheduler.yield(), never block the main thread for >50ms |
| CLS | Elements jumping around | Always set explicit width/height/aspect-ratio on images and containers |
| Meta Tags | First impression in search results | Title + description + OG image = complete social preview |
| Schema.org | Structured data for rich snippets | FAQ schema unlocks dropdowns, Article schema unlocks knowledge panels |
| SQL Injection | User input as executable code | Parameterized queries — never concatenate user input into SQL |
| XSS | Injected scripts steal data | Sanitize on input, encode on output, CSP as last line of defense |
| Path Traversal | Directory manipulation | path.basename() + resolve validation — never trust filename input |
| Rate Limiting | Traffic firewall | Sliding window for accuracy, token bucket for controlled bursts |
| Security Headers | Browser-level defenses | CSP + HSTS + X-Frame-Options = baseline protection |