Abbottabad, KPK
BlogMay 22, 2026

Optimizing SEO, Dynamic OG Images, and Metadata in Next.js App Router

Haseeb Gul
Search engine visibility and social media link preview engagement are pivotal metrics for modern production web applications. When links are shared across platforms like Twitter, LinkedIn, or Discord, high-impact social preview cards directly drive click-through rates (CTR). The Next.js App Router provides built-in Metadata APIs, automated canonical URL routing, and edge-runtime image generation via @vercel/og (next/og). By leveraging these features, developers can move away from static metadata and dynamically build customized, edge-cached social cards and structured schemas for every route. Next.js unifies client-side metadata management, social card generation, and semantic schema markup into server-evaluated modules:
SEO Feature
Next.js Architecture
Primary Benefit & Core Purpose
Dynamic MetadatagenerateMetadata() exportGenerates titles, descriptions, canonical links, and robots directives per request
OG Social Cardsnext/og (ImageResponse)Renders dynamic HTML/JSX into PNG images at Edge Runtime with sub-100ms cold starts
Structured SchemasJSON-LD Script InjectionShips semantic JSON-LD structures (Person, WebSite, Article) for Google Rich Snippets
Sitemap & Robotssitemap.ts & robots.tsGenerates automated XML search engine routes to streamline web crawler indexing
In the App Router, page routes export an async generateMetadata function to fetch dynamic content (e.g., CMS posts, API data) and return strongly typed Metadata objects. Defining metadataBase in your root layout ensures all relative image paths resolve into absolute URLs:
src/app/[slug]/page.tsx
import { Metadata } from "next";
import { baseURL } from "@/app/resources/config";
import { person, home } from "@/app/resources/content";

interface Props {
params: Promise<{ slug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;

// In production, replace with actual CMS/Database call
const title = `${home.title} | ${slug || "Portfolio"}`;
const description = home.description;
const ogImage = `${baseURL}/api/og?title=${encodeURIComponent(title)}`;

return {
  title,
  description,
  metadataBase: new URL(baseURL),
  alternates: {
    canonical: `/${slug || ""}`,
  },
  openGraph: {
    title,
    description,
    url: `${baseURL}/${slug || ""}`,
    siteName: person.name,
    images: [
      {
        url: ogImage,
        width: 1200,
        height: 630,
        alt: title,
      },
    ],
    type: "website",
  },
  twitter: {
    card: "summary_large_image",
    title,
    description,
    images: [ogImage],
  },
  robots: {
    index: true,
    follow: true,
    googleBot: {
      index: true,
      follow: true,
      "max-image-preview": "large",
    },
  },
};
}
Using ImageResponse from next/og inside an App Router Route Handler (api/og/route.tsx), you can build social cards using standard Flexbox JSX layout rules. Running on the Edge Runtime guarantees near-instant responses globally:
src/app/api/og/route.tsx
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";

export const runtime = "edge";

export async function GET(req: NextRequest) {
try {
  const { searchParams } = new URL(req.url);
  const title = searchParams.get("title") || "Haseeb Gul | Frontend Web Developer";

  return new ImageResponse(
    (
      <div
        style={{
          height: "100%",
          width: "100%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          backgroundColor: "#0d0f12",
          color: "#ffffff",
          padding: "60px",
          fontFamily: "sans-serif",
          border: "12px solid #1f242d",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
          <div
            style={{
              width: "16px",
              height: "16px",
              borderRadius: "50%",
              backgroundColor: "#22c55e",
            }}
          />
          <span style={{ fontSize: "20px", color: "#a1a1aa", fontWeight: 600 }}>
            haseebgul.dev
          </span>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
          <h1 style={{ fontSize: "56px", fontWeight: "bold", lineHeight: 1.1 }}>
            {title}
          </h1>
          <p style={{ fontSize: "24px", color: "#a1a1aa" }}>
            Next.js & React Architectures • Performance • Web Engineering
          </p>
        </div>

        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            borderTop: "1px solid #27272a",
            paddingTop: "24px",
          }}
        >
          <span style={{ fontSize: "18px", color: "#71717a" }}>
            Open Graph Card Engine
          </span>
          <span style={{ fontSize: "18px", color: "#3b82f6", fontWeight: 600 }}>
            Read Article →
          </span>
        </div>
      </div>
    ),
    {
      width: 1200,
      height: 630,
    }
  );
} catch (e) {
  return new Response(`Failed to generate image`, { status: 500 });
}
}
Structured data allows search engines like Google to accurately parse entity relationships (such as developer profiles, article publishing metadata, or organization details). We inject structured JSON-LD data as a server component <script> element:
src/components/seo/PersonSchema.tsx
import { baseURL } from "@/app/resources/config";

export function PersonSchema() {
const jsonLd = {
  "@context": "https://schema.org",
  "@type": "Person",
  name: "Haseeb Gul",
  url: baseURL,
  jobTitle: "Frontend Web Developer",
  worksFor: {
    "@type": "Organization",
    name: "Firnas Tech",
  },
  sameAs: [
    "https://linkedin.com/in/haseeb-gul",
    "https://github.com/haseeb-gul"
  ],
  knowsAbout: [
    "React.js",
    "Next.js",
    "JavaScript",
    "Tailwind CSS",
    "Web Performance"
  ]
};

return (
  <script
    type="application/ld+json"
    dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
  />
);
}
SEO Optimization Takeaways
  1. Always define metadataBase in your root layout to eliminate broken image paths during link preview rendering.
  2. Test link previews using official debugging tools like the LinkedIn Post Inspector and Twitter Card Validator.
  3. Embed valid JSON-LD schemas to help search engines present Rich Results for your user profile and dynamic blog posts.