How do I recover the reset password token from Supabase in React?

Viewed 809

I'm a new developer and this is my first time posting to Stack Overflow

I'm using supabase for my db and authentication on my React app. I'm trying to integrate their 'Reset Password' feature (which emails you a link that includes the token in it), but I'm having a hard time recovering the token from the URL when I click on it and am rerouted to my app.

The Supabase documantation says this: When the user clicks the reset link in the email they will be forwarded to: <SITE_URL>#access_token=x&refresh_token=y&expires_in=z&token_type=bearer&type=recovery Your app must detect type=recovery in the fragment and display a password reset form to the user.

When I click the link, it generates a url like this: https://mysupabaseurl/auth/v1/verify?token=zpJG16Xr3kjCUZKUI_WOwQ&type=recovery&redirect_to=http://mysiteurl/

Here is what I have in my code to try to grab that token:

const params = new URLSearchParams(window.location.hash);

  const accessToken = params.get("access_token");

  console.log(accessToken);

I've also tried:

const params = new URLSearchParams(window.location.search);

  const accessToken = params.get("access_token");

  console.log(accessToken);
1 Answers

access_token is a fragment and not a query param, you can see how we do it in the javascript client here:

https://github.com/supabase/gotrue-js/blob/8c6373b9fa11982cb5011df0a273498e3196b302/src/GoTrueClient.ts#L111

getParameterByName('access_token')

where https://github.com/supabase/gotrue-js/blob/8c6373b9fa11982cb5011df0a273498e3196b302/src/lib/helpers.ts#L19

export function getParameterByName(name: string, url?: string) {
  if (!url) url = window?.location?.href || ''
  // eslint-disable-next-line no-useless-escape
  name = name.replace(/[\[\]]/g, '\\$&')
  const regex = new RegExp('[?&#]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url)
  if (!results) return null
  if (!results[2]) return ''
  return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
Related