Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve key-value pair from hash value of the URL

Tags:

javascript

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

like image 651
Aidenhsy Avatar asked Sep 11 '25 16:09

Aidenhsy


1 Answers

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')
like image 198
Miroslav Glamuzina Avatar answered Sep 14 '25 06:09

Miroslav Glamuzina