4
4

More than 1 year has passed since last update.

[Next.js] NextAuth(v3)でGoogle Sign inをつける

Last updated at Posted at 2021-01-03

こちらはv3の実装方法で、v4でかなり変わっています
v4についてはこちらの記事をご覧ください

手順

next-authを追加します。

npm install --save next-auth

pages/api/auth/[...nextauth].jsを作成します。

[...nextauth].jsはこのように実装します。

// [...nextauth.js]
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  // emailのドメイン制限を入れたい場合は以下のcallbacksを入れてください
  callbacks: {
    signIn: async (user, account, profile) => {
      if (
        account.provider === 'google' &&
        profile.verified_email === true &&
        profile.email.endsWith('@example.com')
      ) {
        return Promise.resolve(true)
      } else {
        return Promise.resolve(false)
      }
    },
  },
  // A database is optional, but required to persist accounts in a database
  database: process.env.DATABASE_URL,
}

export default (req, res) => NextAuth(req, res, options)

.env.local を作成し、中身にGOOGLE_CLIENT_IDとGOOGLE_CLIENT_SECRETを記載します。

GOOGLE_CLIENT_ID=xxxxxx
GOOGLE_CLIENT_SECRET=yyyyyyy

client idとsecretは https://console.developers.google.com/apis/credentials で作成・取得できます

あとは認証をかけたいところでuseSession()するだけです。


import React from 'react'
import { signIn, signOut, useSession } from 'next-auth/client'

export default function Page() {
  const [ session, loading ] = useSession()

  return <>
    {!session && <>
      Not signed in <br/>
      <button onClick={signIn}>Sign in</button>
    </>}
    {session && <>
      Signed in as {session.user.email} <br/>
      <button onClick={signOut}>Sign out</button>
    </>}
  </>
}

本番環境にdeployするときは環境変数にNEXTAUTH_URLを設定する必要があります。

NEXTAUTH_URL=https://example.com

環境

next-auth v3.1.0

参考

4
4
3

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
4
4