【Next.js】Googleアカウントでのログイン機能を実装する方法
目次
1. パッケージをインストールする
$ npm install next-auth
2. Google Cloud Platformの設定をする
まずはGoogle Cloud Platformで今回使用する「①クライアントID」と「②クライアントシークレット」の2つを取得するための設定を行います。(OAuth クライアント ID の作成)

Google Cloud Platformのコンソールページから「APIとサービス」→「認証情報」→「認証情報を作成」→「OAuthクライアントID」でOAuth クライアント ID の作成ページを開きます。

「アプリケーションの種類(ウェブアプリケーション)」と「名前」を記入し、「承認済みの JavaScript 生成元」と「承認済みのリダイレクト URI」を画像のように記入して作成します。
OAuth クライアント IDが作成されると「クライアントID」と「クライアントシークレット」の2つが発行されるのでどこかに保存しておきましょう。
3. 環境変数にキーを設定する
取得した「クライアントID」と「クライアントシークレット」をNext.jsの環境変数(.env
ファイル)に追加します。
GOOGLE_CLIENT_ID=[取得したクライアントID]
GOOGLE_CLIENT_SECRET=[取得したクライアントシークレット]
4. pages/api/auth/[…nextauth].tsを作成する
pages/api
内にauth
フォルダを新しく作成し、そこに[…nextauth].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, // 環境変数から取得
}),
],
}
export default NextAuth(authOptions)
5. _app.tsxを編集する
import type {AppProps} from 'next/app'
import {SessionProvider} from 'next-auth/react'
function MyApp({Component, pageProps: {session, ...pageProps}}: AppProps) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
export default MyApp
6. ログインボタンを作成する
ログイン状態に応じて「ログイン」や「ログアウト」ができるボタンを作成します。
import React from "react";
import {useSession, signIn, signOut} from "next-auth/react"
export default function LoginButton() {
// セッション情報を取得
const {data: session} = useSession()
return (
<>
{session
? <button onClick={() => signOut()}>ログアウト</button>
: <button onClick={() => signIn('google')}>ログイン</button>
}
</>
);
};
ここまでで簡単なログイン機能を実装することができました!
次からは、ログインユーザーの情報をデータベースへ保存する手順です。
7. Firebaseにログインデータを保存する
FirebaseのAPIキー等を取得する

まずはFirebaseのプロジェクトを作成します。

次にアプリを追加します。今回はウェブアプリなので</>
ボタンを選択して追加をします。

アプリを追加するとAPIキー等が表示されるので、これをNext.jsに設定していきます。

ただしこの一覧に今回必要なdatabaseURL
が含まれていないので、「Realtime Database」を作成して取得する必要があります。
データベースを作成したら、プロジェクトの設定の「全般」でdatabaseURL
が確認できるようになります。
Google Cloud Platformで「Cloud Firestore API」を有効にする
GCPのライブラリで「Cloud Firestore API」を有効にします。
またFirebaseで「Firestore Database」を作成します。
Firebaseを使うためのライブラリをインストールする
$ npm install firebase
$ npm install @next-auth/firebase-adapter
環境変数にキーを設定する
FIREBASE_API_KEY=XXXXXXXXXX
FIREBASE_APP_ID=XXXXXXXXXX
FIREBASE_AUTH_DOMAIN=XXXXXXXXXX
FIREBASE_DATABASE_URL=XXXXXXXXXX
FIREBASE_PROJECT_ID=XXXXXXXXXX
FIREBASE_STORAGE_BUCKET=XXXXXXXXXX
FIREBASE_MESSAGING_SENDER_ID=XXXXXXXXXX
[…NextAuth].tsに追加する
import NextAuth, {Awaitable, Session} from "next-auth"
import { FirestoreAdapter } from "@next-auth/firebase-adapter"
import { initializeApp } from "firebase/app"
import { getAuth } from 'firebase/auth';
import { getFirestore } from "firebase/firestore";
import GoogleProvider from 'next-auth/providers/google';
import TwitterProvider from "next-auth/providers/twitter"
export const authOptions = {
adapter: FirestoreAdapter({
apiKey: process.env.FIREBASE_API_KEY,
appId: process.env.FIREBASE_APP_ID,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
}),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
}
export default NextAuth(authOptions)
エラー集
Google Cloud Platformで「Cloud Firestore API」が無効になっている
@firebase/firestore: Firestore (9.16.0): Connection GRPC stream error. Code: 7 Message: 7 PERMISSION_DENIED: Cloud Firestore API has not been used in project XXX before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/firestore.googleapis.com/overview?project=XXX then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
Firestore DataBaseが作成されていない
@firebase/firestore: Firestore (9.16.0): Connection GRPC stream error. Code: 5 Message: 5 NOT_FOUND: The database (default) does not exist for project XXX Please visit https://console.cloud.google.com/datastore/setup?project=XXX to add a Cloud Datastore or Cloud Firestore database.
Firestore DataBaseの権限がない
[next-auth][error][adapter_error_getUserByAccount]
https://next-auth.js.org/errors#adapter_error_getuserbyaccount Missing or insufficient permissions. {
message: ‘Missing or insufficient permissions.’,
stack: ‘FirebaseError: Missing or insufficient permissions.’,
name: ‘FirebaseError’
}
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error Missing or insufficient permissions. [FirebaseError: Missing or insufficient permissions.] {
name: ‘GetUserByAccountError’,
code: ‘permission-denied’
}
[…nextauth].tsのファイルの置く場所/ファイル名が間違っている
[next-auth][error][MISSING_NEXTAUTH_API_ROUTE_ERROR]
https://next-auth.js.org/errors#missing_nextauth_api_route_error Cannot find […nextauth].{js,ts} in /pages/api/auth
. Make sure the filename is written correctly. MissingAPIRoute [MissingAPIRouteError]: Cannot find […nextauth].{js,ts} in /pages/api/auth
. Make sure the filename is written correctly.
一見同じファイル名だったのになぜかこのエラーがでました…再度作り直したところなぜかいけました…確認しても違いがわからなかったのですが何か文字が間違っていたかもしれないです。
Firebase adapterのバージョンによるエラー
[next-auth][error][adapter_error_getUserByAccount]
message: ‘Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.’
Firebase adapterのバージョンが2.X.Xだとこのエラーが出てしまいました。エラーの原因がまだ不明ですが「1.0.3」にバージョンを下げることで解消することはできました。
$ npm install @next-auth/firebase-adapter@1.0.3
最近の記事





