OAuth2 in NestJS for Social Login (Google, Facebook, Twitter, etc)

Csaba Apagyi
JavaScript in Plain English
2 min readJun 17, 2021

--

OAuth2 examples for NestJS are amazingly scarce. There’s an open issue since 2018 asking for them, but the replies (1, 2) and resources elsewhere (1, 2) only provide a partial/incomplete overview.

Here I’ll show a full-stack authentication flow, including authenticated requests after the social token has been acquired, optionally for GraphQL as well. You can check a working example in the nestjs-starter repo.

Solution overview:

  • 1, Implement Google auth using @nestjs/passport and passport-google-auth (other providers are very similar).
  • 2, Once redirected back to the app, issue a JWT token, so the app can manage the user’s session.
  • 3, Protect REST and GraphQL endpoints with a JWT strategy.

Step 1. Credits go here for the Google Oauth strategy implementation and showing how to create an OAuth app in Google with screenshots. The code should look like this:

You can now use @UseGuards(GoogleOauthGuard) . You’ll notice that every protected route redirects to Google Auth. We’ll solve this next.

Step 2. Now that the app knows the user we can handle the user’s session within the app. We’ll issue a JWT token and use the corresponding Guard to protect authenticated routes. This is explained in the official docs.

We need to transmit this token between the server and the client. A safe and easy-to-use choice is via a SameSite HttpOnly Cookie. The code should look like this:

Modify the OAuth controller to issue the JWT token:

Step3. We can now use @UseGuards(JwtAuthGuard) to protect authenticated routes. GrapthQL as shown in the docs works out of the box!

Finally, we have end-to-end social auth with NestJS. You’ll find many more cool features in the repo (https://github.com/thisismydesign/nestjs-starter). I’ve also written about an MVC setup combining Next.js and NestJS, and Automagically Typed GraphQL Queries and Results with Apollo.

More content at plainenglish.io

--

--