# AI-Driven SEO: Building a Next.js Site That Writes & Optimizes Its Own Pages

# Introduction

AI is no longer just a chatbot sitting on your landing page. The real opportunity? A website that generates, optimizes, updates, and improves its own SEO pages automatically.

In this deep-dive tutorial, we’ll build a **production-grade AI-driven SEO system using Next.js** that:

*   Auto-generates long-form content
    
*   Optimizes titles, meta tags & schema
    
*   Performs keyword clustering
    
*   Rewrites underperforming pages
    
*   Auto-internal-links content
    
*   Supports ISR & Edge caching
    
*   Works with App Router
    
*   Is monetizable & scalable
    

# Architecture Overview

```markdown
User Search → Keyword Discovery → AI Content Generation
              ↓
         SEO Optimization
              ↓
      Save to Database (MDX)
              ↓
  Next.js ISR → Cached Page
              ↓
Analytics Feedback → AI Rewrites
```

# Tech Stack

*   Next.js 16 (App Router)
    
*   OpenAI / Anthropic / Gemini API
    
*   Prisma + PostgreSQL
    
*   MDX
    
*   Vercel Edge Functions
    
*   Google Search Console API
    
*   OpenAI embeddings for clustering
    

# Implementation

## Step 1 — Project Setup

```shell
npx create-next-app@latest ai-seo-engine
cd ai-seo-engine
npm install openai prisma @prisma/client gray-matter remark remark-html
```

Initialize Prisma:

```markdown
npx prisma init
```

## Step 2 — Database Schema

```typescript
// prisma/schema.prisma

model Page {
  id           String   @id @default(uuid())
  slug         String   @unique
  title        String
  content      String
  metaTitle    String
  metaDesc     String
  keywords     String[]
  score        Float?
  impressions  Int?
  clicks       Int?
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
}
```

Run:

```shell
npx prisma migrate dev
```

## Step 3 — AI Content Generator

Create a new file at /lib/ai.ts

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY!,
});

export async function generateSEOPage(keyword: string) {
  const prompt = `
  Write a 2000 word SEO optimized article targeting:
  "${keyword}"

  Requirements:
  - Proper H1, H2, H3 structure
  - FAQ section
  - Include internal linking suggestions
  - Add JSON-LD schema
  - Use NLP semantic variations
  `;

  const completion = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: prompt }],
    temperature: 0.7,
  });

  return completion.choices[0].message.content;
}
```

## Step 4 — API Route to Generate & Save Pages

Create a new file at - app/api/generate/route.ts

```typescript
import { generateSEOPage } from "@/lib/ai";
import { prisma } from "@/lib/prisma";
import slugify from "slugify";

export async function POST(req: Request) {
  const { keyword } = await req.json();

  const content = await generateSEOPage(keyword);
  const slug = slugify(keyword, { lower: true });

  const page = await prisma.page.create({
    data: {
      slug,
      title: keyword,
      content,
      metaTitle: `${keyword} - Complete Guide`,
      metaDesc: `Learn everything about ${keyword}.`,
      keywords: [keyword],
    },
  });

  return Response.json(page);
}
```

## Step 5 — Dynamic SEO Pages (ISR Enabled)

Create a new file at - /app/\[slug\]/page.tsx

```typescript
import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";

export const revalidate = 60 * 60; // 1 hour ISR

export async function generateMetadata({ params }) {
  const page = await prisma.page.findUnique({
    where: { slug: params.slug },
  });

  if (!page) return {};

  return {
    title: page.metaTitle,
    description: page.metaDesc,
  };
}

export default async function Page({ params }) {
  const page = await prisma.page.findUnique({
    where: { slug: params.slug },
  });

  if (!page) return notFound();

  return (
    <article className="prose mx-auto py-12">
      <h1>{page.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: page.content }} />
    </article>
  );
}
```

## Step 6 — Automatic Internal Linking Engine

We improve topical authority by auto-linking pages.

```typescript
export function autoInternalLinks(content: string, pages: string[]) {
  pages.forEach((keyword) => {
    const regex = new RegExp(`\\b${keyword}\\b`, "gi");
    content = content.replace(
      regex,
      `<a href="/${keyword.toLowerCase().replace(/\s/g, "-")}">${keyword}</a>`
    );
  });

  return content;
}
```

Use embeddings to cluster related topics:

```typescript
export async function getEmbedding(text: string) {
  const res = await client.embeddings.create({
    model: "text-embedding-3-small",
    input: text,
  });

  return res.data[0].embedding;
}
```

Then compute cosine similarity to auto-suggest related links.

## Step 7 — AI Meta Optimization

Instead of hardcoding metadata:

```typescript
export async function generateMeta(content: string) {
  const prompt = `
  Generate SEO meta title (60 chars) and meta description (155 chars)
  for this content:

  ${content.slice(0, 2000)}
  `;

  const res = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: prompt }],
  });

  return res.choices[0].message.content;
}
```

## Step 8 — Schema Markup Auto Injection

```typescript
export function generateFAQSchema(faqs: { q: string; a: string }[]) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: faqs.map((faq) => ({
      "@type": "Question",
      name: faq.q,
      acceptedAnswer: {
        "@type": "Answer",
        text: faq.a,
      },
    })),
  };
}
```

Inject:

```typescript
<script
  type="application/ld+json"
  dangerouslySetInnerHTML={{
    __html: JSON.stringify(schema),
  }}
/>
```

## Step 9 — Performance-Based AI Rewriting

Connect to Search Console API:

```typescript
async function updatePerformance(slug: string) {
  // fetch impressions + clicks
  // if CTR < threshold → rewrite intro & title
}
```

Rewrite with AI:

```typescript
export async function improveCTR(title: string) {
  const prompt = `
  Rewrite this SEO title to maximize CTR:
  "${title}"
  `;

  const res = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: prompt }],
  });

  return res.choices[0].message.content;
}
```

## Step 10 — Scheduled Regeneration (Self-Healing SEO)

Use Vercel cron:

```typescript
export async function GET() {
  const lowPerforming = await prisma.page.findMany({
    where: {
      impressions: { gt: 100 },
      clicks: { lt: 10 },
    },
  });

  for (const page of lowPerforming) {
    const improvedTitle = await improveCTR(page.metaTitle);
    await prisma.page.update({
      where: { id: page.id },
      data: { metaTitle: improvedTitle },
    });
  }

  return Response.json({ success: true });
}
```

# Advanced Scaling Ideas

### Keyword Expansion Engine

*   Scrape Google suggestions
    
*   Use embeddings for clustering
    
*   Auto-generate content clusters
    

### Programmatic SEO

Generate thousands of pages like:

```typescript
/best-{tool}-for-{industry}
/how-to-use-{framework}-with-{tool}
```

### Multi-Language SEO

Use AI for:

*   Translation
    
*   Localized keyword research
    
*   hreflang auto-generation
    

# Deployment Strategy

*   Use **Edge runtime for generation**
    
*   Use **ISR for caching**
    
*   Use **CDN for global SEO**
    
*   Store content in DB + fallback static export
    
*   Add Redis caching for embeddings
    

# Monetization Models

*   Affiliate SEO
    
*   SaaS feature (AI content engine)
    
*   Content-as-a-Service API
    
*   Automated niche sites
    
*   AI-powered landing page builder
    

# Risks & How To Avoid Them

| Risk | Mitigation |
| --- | --- |
| Thin AI content | Add human review loop |
| Google spam detection | Add originality scoring |
| Keyword cannibalization | Embedding clustering |
| Duplicate content | AI uniqueness scoring |

# Final Result

You now have a fully automatic system with:

*   Self-writing pages
    
*   Self-optimizing metadata
    
*   Smart internal linking
    
*   Performance feedback loop
    
*   ISR + Edge powered SEO engine
    

# Why This Is a Massive Opportunity

Google rewards:

*   Topical authority
    
*   Fresh content
    
*   Internal linking depth
    
*   Structured data
    
*   Behavioral improvements
    

An AI-driven SEO engine can do this **at scale** faster than any human team. If you're building something ambitious (like your own dev-focused AI SaaS or high-traffic blog), this architecture can literally become your growth engine.
