I need to connect google oAuth2 to the frontend in react typescript, but I don't know how to redirect to port 3001

Viewed 94

On the backend we use nestjs typescript which run on port 3000:


    import { PassportStrategy } from '@nestjs/passport';
    import { Strategy, VerifyCallback } from 'passport-google-oauth20';
    import { config } from 'dotenv';
    
    import { Injectable } from '@nestjs/common';
    
    config();
    
    @Injectable()
    export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
      constructor() {
        super({
          clientID: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_SECRET,
          callbackURL: 'http://localhost:3000/auth/redirect',
          scope: ['email', 'profile'],
        });
      }
    
      async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
        const { name, emails, photos, id } = profile;
        const user = {
          googleId: id,
          email: emails[0].value,
          firstName: name.givenName,
          lastName: name.familyName,
          picture: photos[0].value,
          accessToken,
        };
    
        done(null, user);
      }
    }

In the frontend we run 3001 and after I choose the google account it's have to be redirect to a page in http://localhost:3001/role-selection.


        const googleAuth = () => {
            window.open(`http://localhost:3000/auth/redirect`, '_self');
            if (token) navigate('role-selection');
        };
        return (
            <Container onClick={googleAuth}>
                <Image src={googleIcon} />
                <Typography>{`${t('GoogleAuthButton.googleAuth')}`}</Typography>
            </Container>
        );
    }

That's the google button component. How can I connect this? I also accept answers in portuguese :D, please guys help me.

1 Answers

I could resolve this by myself and want to post the solution: It's my cotroller file:


    @Get('redirect')
      @UseGuards(AuthGuard('google'))
      googleAuthRedirect(@Req() req, @Res() res) {
        this.authService.googleSignUp(req);
        res.redirect('http://localhost:3001/role-selection');
      }

I hope that can help somebody else.

Related