LoginSignup
2
0

More than 1 year has passed since last update.

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

Posted at

こちらはv4の実装方法です

手順

next-authを追加します。

npm install --save next-auth

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

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

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

const options = {
  providers: [
    GoogleProviders({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async signIn({ account, profile}) {
      if (
        account.provider === 'google' &&
        profile.email_verified &&
        profile.email.endsWith('@example.com')
      ) {
        return true
      } else {
        return false
      }
    },
  },
  database: process.env.DATABASE_URL,
}

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

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

GOOGLE_CLIENT_ID=xxxxxx
GOOGLE_CLIENT_SECRET=yyyyyyy
NEXTAUTH_URL=http://localhost:3000

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

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


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

export default function Page() {
  const { data: session, status } = 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 v4.10.3

参考

https://next-auth.js.org/getting-started/example
https://next-auth.js.org/providers/google

2
0
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
0