How do I navigate back to my React app after calling NestJS GoogleAuth login route in a MonoRepo

Viewed 33

So this is my first project with NestJS and I'm running into a bit of a brick wall. I setup Google OAuth2.0 login with NestJs just fine. I call the routes directly in my browser just fine and it works.

The issue is how do I call these routes in my react app?

Auth.controller.js

@Controller('auth')
export class AuthController {
  @Get('google/login')
  @UseGuards(GoogleAuthGuard)
  async googleLogin() {
    return { msg: 'Google Authetication' };
  }
  @Get('google/redirect')
  @UseGuards(GoogleAuthGuard)
  async handleRedirect(): Promise<{ msg: string }> {
    return { msg: 'ok' };
  }
}

(CRA React) App.js

function App() {
  const [loggedIn, setLoggedIn] = useState(false);
  
  async function handleSignOn() {
    const res = await axios.get("http://localhost:3001/auth/google/login");
    console.log(res);
    return res?.msg === "ok" ? setLoggedIn(true) : setLoggedIn(false);
  }
  return (
    <div>
      <button
        style={{ width: "10em", height: "fit-content" }}
        onClick={handleSignOn}>
        {" sign in "}
      </button>

      <h3> {String(loggedIn)}</h3>
    </div>
  );
}

This is currently what I have. With the current Axios.get call I'm not getting the google login popup when I click the button. I tried doing a direct redirect which works fine but then I get stuck at the API response page.

I'm sure there is something missing but I can't find any tutorials on this and not quite sure what I'm missing here.

1 Answers

So basically you need to do the Google SSO part in react and then pass over the data to backend, as you do ajax call, you won't be redirected from the SPA to Google popup. Here is a more detailed answer to this. Hope it helps. https://stackoverflow.com/a/66255630/3140629

Related