Web Practical Guide with Claude Code
Learn about web practical guide using Claude Code. Practical tips and code examples included.
WebセキュリティヘッダーをClaude Codeで正しく設定する
Webアプリケーションのセキュリティには適切なHTTPヘッダー設定が不可欠です。しかし、各ヘッダーの役割や正しい値の設定は複雑です。Claude Codeを使えば、プロジェクトに合ったセキュリティヘッダーを正確に設定できます。
Content Security Policy(CSP)
適切なCSP設定
> Next.jsアプリ用のCSPヘッダーを設定して。
> 要件:
> - インラインスクリプトはnonce方式
> - Google Analyticsを許可
> - 外部フォントを許可
> - レポートURIを設定
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import crypto from 'crypto';
export function middleware(request: NextRequest) {
const nonce = crypto.randomBytes(16).toString('base64');
const response = NextResponse.next();
const csp = [
`default-src 'self'`,
`script-src 'self' 'nonce-${nonce}' https://www.googletagmanager.com`,
`style-src 'self' 'unsafe-inline' https://fonts.googleapis.com`,
`font-src 'self' https://fonts.gstatic.com`,
`img-src 'self' data: https:`,
`connect-src 'self' https://www.google-analytics.com`,
`frame-ancestors 'none'`,
`base-uri 'self'`,
`form-action 'self'`,
`report-uri /api/csp-report`,
].join('; ');
response.headers.set('Content-Security-Policy', csp);
response.headers.set('x-nonce', nonce);
return response;
}
主要セキュリティヘッダー一覧
> すべてのセキュリティヘッダーを一括設定するミドルウェアを作成して。
// Express.jsでの設定例
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: { /* 上記CSP設定 */ },
strictTransportSecurity: {
maxAge: 63072000, // 2年
includeSubDomains: true,
preload: true,
},
referrerPolicy: {
policy: 'strict-origin-when-cross-origin',
},
frameguard: { action: 'deny' },
}));
// Helmetがカバーしない追加ヘッダー
app.use((req, res, next) => {
res.setHeader('Permissions-Policy',
'camera=(), microphone=(), geolocation=(), payment=(self)');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
next();
});
各ヘッダーの解説
| ヘッダー | 目的 | 推奨値 |
|---|---|---|
| Content-Security-Policy | XSS・インジェクション防止 | プロジェクト固有 |
| Strict-Transport-Security | HTTPS強制 | max-age=63072000; includeSubDomains; preload |
| X-Content-Type-Options | MIMEスニッフィング防止 | nosniff |
| X-Frame-Options | クリックジャッキング防止 | DENY |
| Referrer-Policy | リファラー情報制御 | strict-origin-when-cross-origin |
| Permissions-Policy | ブラウザ機能制限 | 必要な機能のみ許可 |
CSPレポートの受信
CSP違反レポートを受信して分析するエンドポイントもClaude Codeで構築できます。
// pages/api/csp-report.ts
export default function handler(req, res) {
if (req.method === 'POST') {
const report = req.body['csp-report'];
console.warn('CSP違反:', {
blockedUri: report['blocked-uri'],
violatedDirective: report['violated-directive'],
documentUri: report['document-uri'],
});
}
res.status(204).end();
}
セキュリティ監査
「SecurityHeaders.com でA+評価を取りたい」とClaude Codeに伝えれば、不足しているヘッダーを特定して追加提案してくれます。
Summary
Claude Codeを使えば、Webセキュリティヘッダーの設定を正確かつ包括的に行えます。セキュリティ監査ガイドやCORS設定ガイドも合わせて参考にしてください。
セキュリティヘッダーの詳細はMDN Web Docs - HTTPヘッダーおよびSecurityHeaders.comを参照してください。
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.