Skip to content

Instantly share code, notes, and snippets.

@joshpetit
Created June 26, 2024 03:34
Show Gist options
  • Save joshpetit/91b9cef8c02ba8e6fe74efa858af8b75 to your computer and use it in GitHub Desktop.
Save joshpetit/91b9cef8c02ba8e6fe74efa858af8b75 to your computer and use it in GitHub Desktop.
Supabase and nextjs password reset page
"use client";
import { SubmitButton } from "../login/submit-button";
import { redirect } from "next/navigation";
import { createBrowserLocaleClient } from "@/utils/supabase/client";
import { useEffect, useState } from "react";
export default function ResetPassword() {
const supabase = createBrowserLocaleClient();
const [accessToken, setAccessToken] = useState("");
const [refreshToken, setRefreshToken] = useState("");
const [resetPasswordError, setResetPasswordError] = useState("");
useEffect(() => {
const hashParams = new URLSearchParams(window.location.hash.substring(1));
const access_token = hashParams.get("access_token");
const refresh_token = hashParams.get("refresh_token");
if (!access_token || !refresh_token) {
return redirect("/login");
}
setAccessToken(access_token);
setRefreshToken(refresh_token);
}, []);
const resetPassword = async (formData: FormData) => {
const password = formData.get("password") as string;
const res = await supabase.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
});
console.log(res);
if (!password) {
return;
}
const { error } = await supabase.auth.updateUser({
password,
});
if (error) {
console.log(error);
setResetPasswordError(error.message);
return;
}
return redirect("/admin");
};
return (
<div className="my-auto">
<div className="shadow-xl p-10">
<h2 className="text-3xl mx-auto my-auto font-bold text-center">
Reset Password
</h2>
<span className="text-gray-500 text-center">
Enter a new password for your account.
</span>
<form>
<div className="mt-8 space-y-6">
<input type="hidden" name="token" />
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
New Password
</label>
<input
id="password"
name="password"
type="password"
autoComplete="new-password"
required
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
</div>
<SubmitButton
className="w-full px-4 py-2 font-medium text-white bg-green-600 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
formAction={resetPassword}
pendingText="Submitting..."
>
Submit
</SubmitButton>
{resetPasswordError ? (
<div className="text-sm text-red-500 text-center">
{resetPasswordError}
</div>
) : null}
</div>
</form>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment