Search code examples
reactjstypescriptaxiosnestjsgoogle-oauth

Receiving token by client after google authorization


I am building a fullstack application on React+TS and Nest. In Nest I have a working logic for redirecting to authorization via google.

@Get('google')
  @UseGuards(AuthGuard('google'))
  async googleLogin() {
    // This handler will automatically redirect the user to the VK page for authentication
  }

  @Get('google/callback')
  @UseGuards(AuthGuard('google'))
  async googleAuthRedirect(@Req() req, @Res() res) {
    return this.authService.googleLogin(req);
    // returns {access_token, refresh_token{enter image description here
  }

When I fetch localhost:3333/auth/google.
it redirects me to the authorization page, and after authorization to localhost:3333/auth/google/callback, which returns the token object: {access_token:"", refresh_token:""}

/auth/google/callback

I am facing a problem, how to get this token object from the client side(React)? I can't seem to just use axios.get(/auth/google/callback) because each callback is different.

So, my goal is to make such logic:

  1. client clicks on the button

  2. it redirects him to (server)/auth/google

  3. user completes the form

  4. tokens from auth/google/callback are saved in localstorage via React

  5. redirect to localhost:5173/poll

If it was a regular get route, I would just access it via axios.get(auth/google/callback). But apparently it throws an error


Solution

  • I've found out that we can write data to cookies from the backend as well. So, I changed my controller function

    async googleAuthRedirect(@Req() req, @Res() res) {
      const authTokens = await this.authService.getVkTokens(req);
      res.cookie('refresh_token', authTokens.refreshToken);
      res.cookie('access_token', authTokens.accessToken);
    }
    

    Used cookie-parser here