How to use Password Reset API in Supabase Auth with the help of nextjs?

How to use Password Reset API in Supabase Auth with the help of nextjs?

Β·

3 min read

Hi πŸ‘‹ brothers and sisters, in this blog, I would tell you how you can use the password reset in supabase auth API.

πŸŒ‹πŸŒ‹πŸŒ‹Firstly, you need to implement the basic supabase in nextjs.

After you have implemented auth in your next js app.

Then you need to make a reset.jsx in your pages folder. This file will be the route for the user to submit the email and click the button to send a password recovery email. Then paste this πŸ‘‡ code.

import { supabase } from "../utils/supabase";
import React, { useState } from "react";
import toast from "react-hot-toast";

function reset() {
  const [email, setEmail] = useState(null);

  const handleSubmit = async (e) => {
    console.log("name");

    e.preventDefault();

    const notification = toast.loading("Sending Email....");

    try {
      const { data, error } = await supabase.auth.api.resetPasswordForEmail(
        email,
        {
          redirectTo: "http://localhost:3000/password-reset", //// this will redirect to us at password-reset page,
          //// you can also set your own page for it.
        }
      );

      if (error) {
        toast.error(error.message, {
          id: notification,
        });
      } else if (data) {
        console.log(data);
        toast.success("Sent", {
          id: notification,
        });
      }
    } catch (error) {
      toast.error("Sorry Error occured", {
        id: notification,
      });
    }
  };

  return (
    <div>
      <form onSubmit={(e) => handleSubmit(e)}>
        <input
          type="email"
          placeholder = "Please enter your email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />

        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default reset;

Now, we have to make our password-reset.jsx file in pages folder.

import React, { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { supabase } from "../utils/supabase";

function PasswordReset() {
  const [password, setPassword] = useState(null);

  const [hash, setHash] = useState(null);

  useEffect(() => {
    setHash(window.location.hash);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const notification = toast.loading("Changing Password");

    try {
      // if the user doesn't have accesstoken
      if (!hash) {
        return toast.error("Sorry, Invalid token", {
          id: notification,
        });
      } else if (hash) {
        const hashArr = hash
          .substring(1)
          .split("&")
          .map((param) => param.split("="));

        let type;
        let accessToken;
        for (const [key, value] of hashArr) {
          if (key === "type") {
            type = value;
          } else if (key === "access_token") {
            accessToken = value;
          }
        }

        if (
          type !== "recovery" ||
          !accessToken ||
          typeof accessToken === "object"
        ) {
          toast.error("Invalid access token or type", {
            id: notification,
          });
          return;
        }

        //   now we will change the password
        const { error } = await supabase.auth.api.updateUser(accessToken, {
          password: password,
        });

        if (error) {
          toast.error(error.message, {
            id: notification,
          });
        } else if (!error) {
          toast.success("Password Changed", {
            id: notification,
          });
        }
      }
    } catch (error) {
      console.log(error);
      toast.error("Sorry Error occured", {
        id: notification,
      });
    }
  };

  return (
    <div>
      <form onSubmit={(e) => handleSubmit(e)}>
        <input
          type="password"
          required
          value={password}
          placeholder="Please enter your Password"
          onChange={(e) => setPassword(e.target.value)}
        />

        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default PasswordReset;

Now you can actually change your password by πŸ‘‡:

  1. Go tohttp://localhost:3000/reset#

  2. Then submit your email

  3. Then go to Gmail or where you will receive an email (from noreply)

  4. Then click on the link provided by supabase

  5. Then give your new password

If you have faced any error or difficulty, feel free to put questions here: Join the Next Dev's server Discord Server!

Congratulations πŸ€“πŸ€“!!!!

Did you find this article valuable?

Support Next Dev by becoming a sponsor. Any amount is appreciated!

Β