PSI MCP × Claude Code

Next.js Core Web Vitals — Before / After ショーケース

Zenn 記事 「PSI MCP × Claude Code で Core Web Vitals を改善する」 で取り上げた 4 つの改善のコード比較。

Lighthouse の Opportunities から 1 項目ずつ拾って、Before の状態と After の差分だけを見る形にしている。

ヒーロー画像 LCP

<img> を next/image に置き換えると <link rel="preload"> が生成され、LCP 要素の発見が早くなる。sizes を省略するとモバイルで不必要に大きい画像を送り続けてしまうので忘れず指定する。

Before
<img
  src="/hero.jpg"
  alt="hero"
  style={{ width: '100%' }}
/>
After
import Image from 'next/image'

<Image
  src="/hero.jpg"
  alt="hero"
  width={1200}
  height={600}
  priority
  sizes="(max-width: 768px) 100vw, 1200px"
/>

フォント FCP / LCP

Google Fonts を <link> で読み込むとレンダリングブロッキングが発生する。next/font に切り替えるとセルフホスティングされ、外部リクエストが消える。

Before
<!-- _document.tsx で直書き -->
<link
  href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP&display=swap"
  rel="stylesheet"
/>
After
import { Noto_Sans_JP } from 'next/font/google'

const noto = Noto_Sans_JP({
  subsets: ['latin'],
  weight: ['400', '700'],
  display: 'swap',
})

export default function RootLayout({ children }) {
  return (
    <html lang="ja" className={noto.className}>
      <body>{children}</body>
    </html>
  )
}

サードパーティスクリプト TBT

チャット系ウィジェットの直書きを next/script の lazyOnload に変えると、全リソース読み込み後に実行されてメインスレッドのブロックがなくなる。afterInteractive はインタラクションと重なるケースがあったため避けた。

Before
<script
  src="https://example-chat.com/widget.js"
></script>
After
import Script from 'next/script'

<Script
  src="https://example-chat.com/widget.js"
  strategy="lazyOnload"
/>

Tailwind CSS の purge Speed Index

app/ ディレクトリ構成に移行した際に content パスが古いままだと purge が効かず、未使用スタイルが大量に含まれてしまう。Lighthouse の「Remove unused CSS」が Opportunities に出ていたら真っ先に疑う場所。

Before
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
  ],
}
After
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
  ],
}

.claude/mcp.json — PSI MCP の接続設定

Next.js プロジェクトのルートにこの設定を置き、Claude Code を再起動すると pagespeed ツールが有効になる。

{
  "mcpServers": {
    "pagespeed": {
      "command": "npx",
      "args": ["-y", "pagespeed-insights-mcp"],
      "env": {
        "PSI_API_KEY": "<YOUR_GOOGLE_CLOUD_API_KEY>"
      }
    }
  }
}