Adding Google OAuth Login to a Node.js and Express API

Adding Google OAuth Login to a Node.js and Express API

The authorization code flow, state checks and account linking, explained without the boilerplate overload.

Social login removes the biggest point of friction in sign-up. Under the hood it is the OAuth 2.0 authorization code flow, and getting a few details right makes it secure.

The flow in four steps

  1. Your API redirects the user to Google with your client id, scopes and a random state value.
  2. The user approves and Google redirects back with a short-lived code and the same state.
  3. Your server exchanges the code for tokens using the client secret.
  4. You read the verified email and profile, then create or link the user and start your own session.

Always check state

Store the state value in a short-lived cookie before redirecting and compare it on callback. A mismatch means the request did not start from your app, so reject it. This blocks login CSRF.

const state = crypto.randomBytes(16).toString("hex");
res.cookie("oauth_state", state, { httpOnly: true, secure: true, maxAge: 600_000 });
res.redirect(buildGoogleAuthUrl({ state }));

Linking accounts

If someone signed up with email and later uses Google with the same verified email, link the Google id to the existing user instead of creating a duplicate. Only link when the provider marks the email as verified.

Do not keep provider tokens you do not need

For plain sign-in you only need the identity. Discard Google's access token after reading the profile and issue your own session or tokens. Fewer secrets stored means fewer secrets to leak.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion