4

I am learning the OAuth2 flow with Google (https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#oauth-2.0-endpoints), I am NOT using Google's JS Client library. At the step where Google returns a hash value to my redirect URL, which looks something like this:

http://localhost:3000/profile#access_token=ya29.A0AfH6SMCKcSSl4-KfeV7oioFYN_LHpJ9Z_cnpY5yHCK4d8U1TdaZ-TXU05XfzNZsmfNA1Csla-f8U3k4Jp9uYzCzmkIJf1qs5k_hle5ArwBm462_TPfuTtn5bbnN-hD5Bn7m9TEpxF3vmez81IU-AgNHhMwgr&token_type=Bearer&expires_in=3599&scope=profile%20https://www.googleapis.com/auth/userinfo.profile

How can I retrieve the values from the hash value like access_token? What I have so far is this which retrieves the hash value without the #:

import React, { useEffect } from 'react';

const Profile = () => {
  useEffect(() => {
    if (window.location.hash) {
      console.log(window.location.hash.substr(1));
    } else {
      console.log('no hash');
    }
  });
  return (
    <div>
      <h1>Profile page</h1>
    </div>
  );
};

export default Profile;

PS: I am using NextJS

1 Answer 1

4

You can use URLSearchParams to make this easier for you.

const urlParams = new URLSearchParams(window.location.hash.substr(1))

You can access values like access_token like so:

urlParams.get('access_token')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.