NextJs Supabase, Reset Password. Email verification token

422 Views Asked by At

I am using NextJs and Supabase to reset user password.

Below is my server action where i am calling resetPasswordForEmail function to send email to client mailbox

export const resetPasswordWithEmail = async (email: string) => {
  'use server';

  const foundUser = await getUserByEmail(email);
  if (!foundUser) {
    return {
          error: [
            {
              id: '1',
              message: 'This email doesnt exist in our database',
            },
          ],
        };
  }

  const { error} = await supabaseClient.auth.resetPasswordForEmail(email);
  if (error) {
    return {
      error: [
        {
          id: '1',
          message: error.message,
        },
      ],
    };
  }
  return {
    success: 'An email has been successfully sent to your mailbox'
  };
}

this is my email template from supabase

<a href="{{.ConfirmationURL}}/api/auth/callback?next=/auth/reset-password" style="display: inline-block; padding: 10px 20px; background-color: #FDAC04; color: #000000; text-decoration: none; border-radius: 5px;">Click here to reset your password</a>

the resent link is the api from my next.js and supabase automatic add two parameter's 'code' & 'hash_token', where i am passing 'code' parameter to the supabase function supabase.auth.exchangeCodeForSession to validate the code. and redirect from the api to reset-password page.

this is the code

export async function GET(request: Request) {
  // The `/auth/callback` route is required for the server-side auth flow implemented
  // by the Auth Helpers package. It exchanges an auth code for the user's session.
  // https://supabase.com/docs/guides/auth/auth-helpers/nextjs#managing-sign-in-with-code-exchange
  const requestUrl = new URL(request.url);
  const code = requestUrl.searchParams.get('code');
  const next = requestUrl.searchParams.get('next');

  if (code) {
    const cookieStore = cookies();
    const supabase = createClientServer(cookieStore);
    await supabase.auth.exchangeCodeForSession(code);
  }

  // URL to redirect to after sign in process completes
  if (next) return NextResponse.redirect(next);
  else return NextResponse.redirect(requestUrl.origin);
}

this function exchangeCodeForSession is throwing an error

Error: 'AuthApiError: invalid request: both auth code and code verifier should be non-empty'

Do you guys have any idea ?

0

There are 0 best solutions below