1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.jsでのFIrebaseの会員登録機能の実装

Posted at

Next.jsでの会員登録機能の実装を紹介します。

公式リファレンス
https://firebase.google.com/docs/auth/web/start?hl=ja
参考動画
https://www.youtube.com/watch?v=2GIMsmDvXls

初期設定

最初にfirebaseConfig.jsの設定をします。
こちらは基本的に、Firebaseで登録した際に、貰える初期コードのままで基本的には大丈夫です。

#firebaseConfig.js

// Import the functions you need from the SDKs you need
import firebase from "firebase/app";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "****",
  authDomain: "****",
  projectId: "****",
  storageBucket: "****",
  messagingSenderId: "****",
  appId: "****",
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const database = getFirestore(app);

export const storage = getStorage(app);

ここからは、新規登録から実装していきます。

新規登録の手順

まずは入力部分の作成します。
動きとしては、input(TextField)を使い、

onChange={(event) => setPassword(event.target.value)}

setPasswordで、入力値を受け取ります。

#register.js
            <TextField
              id="outlined-basic"
              label="sample@gmail.com"
              className="m-auto w-80"
              variant="outlined"
              onChange={(event) => setEmail(event.target.value)}
            />
            <br></br>
            <br></br>
            <label className="text-center my-4">パスワード8文字以上)*</label>
            <br></br>
            <TextField
              id="outlined-basic"
              label="Password"
              type="password"
              variant="outlined"
              className="m-auto w-80"
              onChange={(event) => setPassword(event.target.value)}
            />
            <br></br>
            <br></br>
            <Button
              variant="outlined"
              onClick={SignUp}
              className="m-auto w-80 my-8"
            >
              新規登録
            </Button>
            <br></br>
            <br></br>
            <Button
              variant="outlined"
              onClick={SignUpWithGoogle}
              className="m-auto w-80 "
            >
              Googleで新規登録
            </Button>

そして処理部分を記載します。
普通の登録を行う際は、「createUserWithEmailAndPassword」を用いて、
Google登録をする際は、「 GoogleAuthProvider」を使って認証します。
登録すると、sessionStorageのTokenを持つことになります。


#register.js
import {
  getAuth,
  createUserWithEmailAndPassword,
  GoogleAuthProvider,
  signInWithPopup,
} from "firebase/auth";
import { useState } from "react";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { MuiNavbar } from "../layouts/MuiNavbar";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Head from "next/head";
import Link from "next/link";

export default function Register() {
  const auth = getAuth();
  const router = useRouter();
  const googleProvider = new GoogleAuthProvider();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const SignUp = () => {
    createUserWithEmailAndPassword(auth, email, password)
      .then((response) => {
        sessionStorage.setItem("Token", response.user.accessToken);
        console.log(response.user);
        router.push("/home");
      })
      .catch((err) => {
        alert("emailが既にあります");
      });
  };

  const SignUpWithGoogle = () => {
    signInWithPopup(auth, googleProvider).then((response) => {
      console.log(response.user);
      sessionStorage.setItem("Token", response.user.accessToken);
      router.push("/home");
    });
  };

ログイン方法

ログインの処理についても記載します。

#login.js
        <Box
          component="form"
          className="flex justify-center max-w-7xl "
          noValidate
          autoComplete="off"
        >
          <div>
            <label className="text-center my-4">
              {/* <FontAwesomeIcon icon={faEnvelope} className="w-2" /> */}
              メールアドレス*
            </label>
            <br></br>
            <TextField
              id="outlined-basic"
              label="sample@gmail.com"
              className="m-auto w-80"
              variant="outlined"
              onChange={(event) => setEmail(event.target.value)}
            />
            <br></br>
            <br></br>
            <label className="text-center my-4">パスワード8文字以上)*</label>
            <br></br>
            <br></br>
            <TextField
              id="outlined-basic"
              label="Password"
              variant="outlined"
              type="password"
              className="m-auto w-80"
              onChange={(event) => setPassword(event.target.value)}
            />
            <br></br>
            <br></br>
            <Button
              variant="outlined"
              onClick={SignUp}
              className="m-auto w-80 my-8"
            >
              ログイン
            </Button>
            <br></br>
            <br></br>
            <Button
              variant="outlined"
              onClick={SignUpWithGoogle}
              className="m-auto w-80"
            >
              Googleでログイン
            </Button>

createUserWithEmailAndPasswordの代わりにsignInWithEmailAndPasswordを使って、ログイン処理を実現しています。
また、Googleは同じ処理です。
関数名がregsiter.jsと同じになっているの申し訳ないです。
これでログインの方も完成です。

#login.js

import { app } from "../firebaseConfig";
import {
  getAuth,
  signInWithEmailAndPassword,
  GoogleAuthProvider,
  signInWithPopup,
} from "firebase/auth";
import { useState } from "react";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { MuiNavbar } from "../layouts/MuiNavbar";
import Button from "@mui/material/Button";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Head from "next/head";

export default function Login() {
  const auth = getAuth();
  const router = useRouter();
  const googleProvider = new GoogleAuthProvider();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const SignUp = () => {
    signInWithEmailAndPassword(auth, email, password)
      .then((response) => {
        sessionStorage.setItem("Token", response.user.accessToken);
        console.log(response.user);
        router.push("/home");
      })
      .catch((err) => {
        alert("ログインできません");
      });
  };

  const SignUpWithGoogle = () => {
    signInWithPopup(auth, googleProvider).then((response) => {
      console.log(response.user);
      sessionStorage.setItem("Token", response.user.accessToken);
      router.push("/home");
    });
  };
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?