2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

目標

  • Next.jsでの認証の必要性を理解する。
  • NextAuth.jsを使って認証機能をセットアップする。
  • ブログにGoogleログインを追加し、保護されたページを作る。

1. 認証機能の重要性

ウェブアプリでは、ユーザー管理やセキュリティのために認証が不可欠です。NextAuth.jsはNext.js向けの認証ライブラリで、GoogleやGitHubなどのソーシャルログインを簡単に追加できます。この記事では、ブログにGoogleログインを追加し、保護されたページを作成します。


2. NextAuth.jsのインストール

NextAuth.jsをプロジェクトに導入します。

手順:

ターミナルで以下を実行:

npm install next-auth

3. NextAuth.jsの設定

Googleログインを有効化し、認証フローを構築します。

環境変数の設定:

.env.localに以下を追加:

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
  • NEXTAUTH_SECRETはランダムな文字列(例:openssl rand -base64 32で生成)。
  • Google Client IDとSecretはGoogle Cloud Consoleで取得。

app/api/auth/[...nextauth]/route.tsの作成:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

4. 認証機能の実装

ログイン/ログアウト機能と保護されたページを追加します。

app/layout.tsxの編集:

import '../globals.css';
import Link from 'next/link';
import { auth } from 'next-auth';
import { signIn, signOut } from 'next-auth/react';

export const metadata = {
  title: 'Next.js 2025ブログ',
  description: '2025年の最新技術で作られたブログサイト',
};

export default async function RootLayout({ children }) {
  const session = await auth();

  return (
    <html lang="ja">
      <body className="font-sans antialiased">
        <header className="bg-blue-800 text-white p-4">
          <nav className="max-w-4xl mx-auto flex justify-between items-center">
            <Link href="/" className="text-xl font-bold">ホーム</Link>
            <div className="space-x-4">
              <Link href="/about" className="hover:underline">About</Link>
              {session ? (
                <>
                  <Link href="/dashboard" className="hover:underline">ダッシュボード</Link>
                  <span>{session.user?.name}</span>
                  <button onClick={() => signOut()} className="hover:underline">ログアウト</button>
                </>
              ) : (
                <button onClick={() => signIn('google')} className="hover:underline">Googleでログイン</button>
              )}
            </div>
          </nav>
        </header>
        <main>{children}</main>
        <footer className="bg-gray-200 p-4 text-center text-gray-600">
          © 2025 Next.js学習シリーズ
        </footer>
      </body>
    </html>
  );
}

保護されたページの作成:

app/dashboard/page.tsxを作成:

import { auth } from 'next-auth';
import { redirect } from 'next/navigation';

export default async function Dashboard() {
  const session = await auth();
  if (!session) {
    redirect('/'); // 未ログインならリダイレクト
  }

  return (
    <div className="max-w-2xl mx-auto p-6">
      <h1 className="text-3xl font-bold text-blue-600 mb-4">ダッシュボード</h1>
      <p>ようこそ、{session.user?.name}さん!ここはログインしたユーザーのみが見られるページです。</p>
    </div>
  );
}

実践:認証付きブログ

  • ログイン:Googleアカウントでログイン可能。
  • 保護:ダッシュボードページはログイン済みユーザーのみアクセス可能。
  • ユーザー情報:ヘッダーにユーザー名を表示。

確認

  1. npm run devで起動。
  2. http://localhost:3000にアクセスし、「Googleでログイン」をクリック。
  3. ログイン後、ダッシュボードページを確認。

まとめ

  • NextAuth.jsで簡単に認証機能を追加しました。
  • ブログにGoogleログインと保護されたページを実装しました。

この記事が役に立ったと思ったら、ぜひ「いいね」を押して、ストックしていただければ嬉しいです!あなたのNext.jsプロジェクトにも認証機能を試してみてください!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?