Twitter clone Part8　next authとfirebaseを使ってログインページの実装

# 概要
今回はfirebaseとnext authを使ってログイン機能を実装します。
以下実装後の様子です。

![loginPage.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/f6641c28-39fe-36fd-13a7-244d54ccb629.gif)





# 開発環境

OS:Windows10
IDE:VSCode


```package.json
{
  "name": "",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@heroicons/react": "^1.0.6",
    "next": "12.0.9",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@types/node": "^20.4.2",
    "@types/react": "^18.2.15",
    "autoprefixer": "^10.4.2",
    "eslint": "8.8.0",
    "eslint-config-next": "12.0.9",
    "postcss": "^8.4.5",
    "tailwindcss": "^3.0.18"
  }
}
```

# 実装のポイント





## firebase側の設定をする

### プロジェクトを新規作成

![01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/1f639679-c839-cd3c-6a09-3424241ffaea.png)

![02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/8526f5cc-3d01-20fc-7b39-14b2f6f1d69e.png)


![03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/cb13e9bd-7f22-d604-f3d1-b6db9ca7fa75.png)



### ウェブアプリを登録　apiKey

![04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/a1693b29-2adf-ef6e-901d-4c45e4a01f7e.png)

![05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/b5a8eeee-608e-a98d-9c9e-fd63304c82b3.png)

![06.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/54a0aac0-caa7-b99d-2e85-7c893dc7885a.png)


### Authenticationの設定　ログインプロバイダにgoogleを加える

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/94e0c2e9-7116-77bf-bf2c-dcf60d2cb8f7.png)


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/27ddbf69-6dc0-b035-b059-bfdbe8c162a2.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/0992a1bc-dbf4-4e4e-69cd-c7d0019c3022.png)




## Next.js　（next auth）

### 環境変数ファイルを作成　.env.local

#### firebase.jsのパラメータを設定
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/8adc7627-c17a-e38b-2398-f6139b071055.png)


#### [...nextauth].jsで使うパラメータを設定

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/d92309a6-5b8c-e3ed-7144-f1bbe1385f95.png)

### コード部分の実装

## pages/api/auth/[...nextauth].js  nextauthの設定ファイル
```diff_jsx:[...nextauth].js
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"


export default NextAuth({
    providers:[
        GoogleProvider({
            clientId:process.env.GOOGLE_CLIENT_ID,
            clientSecret:process.env.GOOGLE_CLIENT_SECRET,
        }),
    ],

    pages:{
        signin: "/auth/signin"
    }
})
```

## pages/auth/signin ログインページ
```diff_jsx:signin.jsx
import {getProviders, signIn} from "next-auth/react";

export default function signin({providers}){
    return(
        <div className="flex justify-center mt-20 space-x-4">
        <img
          src="https://cdn.cms-twdigitalassets.com/content/dam/help-twitter/en/twitter-tips/desktop-assets/ch-01/ch12findphone.png.twimg.1920.png"
          alt="twitter image inside a phone"
          className="hidden object-cover md:w-44 md:h-80 rotate-6  md:inline-flex"
        />
        <div className="">
          {Object.values(providers).map((provider) => (
            <div className="flex flex-col items-center">
              <img
                className="w-36 object-cover"
                src="https://help.twitter.com/content/dam/help-twitter/brand/logo.png"
                alt="twitter logo"
              />
              <p className="text-center text-sm italic my-10">
                This app is created for learning purposes
              </p>
              <button
                onClick={() => signIn(provider.id, { callbackUrl: "/" })}
                className="bg-red-400 rounded-lg p-3 text-white hover:bg-red-500"
              >
                Sign in with {provider.name}
              </button>
            </div>
          ))}
        </div>
      </div>
    )
}

export async function getServerSideProps(){
    const providers = await getProviders();
    return{
        props:{providers
        },
    };
}
```

## root/firebase.js  firebaseの設定ファイル
```diff_jsx:firebase.js

import {initializeApp,getApp,getApps} from "firebase/app";
import {getFirestore, getFireStore} from "firebase/firestore";
import {getStorage} from "firebase/storage";
import { get } from "http";


const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGE_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
    measurementId:process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENTID_ID,
};

const app = !getApps().length ? initializeApp(firebaseConfig) :getApp();
const db = getFirestore();
const storage = getStorage();
export{app,db, storage}
```


## .env.local　gitignoreされている

``` .env.local
GOOGLE_CLIENT_ID=74XXXXXXXXXXXXXXXXXXXX795.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=GOXXXXXXXXXXXXXXXXXXXXXXXXFzV
NEXT_PUBLIC_FIREBASE_API_KEY=AIzXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFu0
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=twitterXXXXXXXXXXXX.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=twitter-clone-fukushu
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=twitter-clone-fukushu.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGE_SENDER_ID=740XXXXXXXXXXX
NEXT_PUBLIC_FIREBASE_APP_ID=1:740XXXXXXXXXXXXXXXXXXXXXX
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=G-JXXXXXXX

```




## リダレクトURL関係のエラーに対処するため　Google Cloudの設定をする

### リダレクトURL関係のエラー　原因はGoogleコンソール側の設定
ログインに失敗するのでこれを解消するために googleConsole側で設定を行います。
以下

![2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/19c5581e-5751-a6d2-b6c8-7d7ea2bdda76.png)



### プロジェクトを開く
プロジェクトが作成されているので、開きます。

https://cloud.google.com/?hl=ja


プロジェクトを選択します。
![0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/919429bf-b17b-ed05-4611-3d19d89b4cbe.png)

認証情報のOAuth2.0クライアントIDを開いて、クライアントIDとクライアントシークレットが一致していることを確認します。


![1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/84070a75-029f-7e3b-816f-09232f1e0055.png)

承認済みのリダイレクトURIに「http://localhost:3000/api/auth/callback/google」を加えます。


![3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/9a3c948c-836f-4b31-1336-c49b5f6febc2.png)




設定後googleアカウントでログイン画面が表示されます。







# 参考

## css

## javascript

## Next.js

### Next Auth

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

https://github.com/nextauthjs/next-auth-example/blob/main/pages/api/auth/%5B...nextauth%5D.ts

## React

## firebase



## その他

### Google Cloud



Udemy
76. Complete the signin page


https://www.udemy.com/course/react-js-tutorial/learn/lecture/32461752#overview

githubコミット分

https://github.com/RYA234/twitter-clone/commit/1ec9c3cbe4da9f957f4def7071f2ab397280d3fa