Episode 8 of 21
The Redirect URI
Understand and configure the redirect URI — the URL Google sends the user back to after they authenticate.
The Redirect URI
The Redirect URI (also called Callback URL) is the URL Google sends the user back to after they log in and grant permission. This URL must match exactly between your code and the Google Developer Console.
How It Works
1. User clicks "Login with Google"
2. Your app sends them to Google with:
- Client ID
- Scope (what data you want)
- Redirect URI (where to send them back)
3. User logs in and grants permission
4. Google redirects to YOUR redirect URI with a code:
http://localhost:3000/auth/google/redirect?code=AUTHORIZATION_CODE
Setting the Redirect URI
// In your Passport strategy:
new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL: '/auth/google/redirect' // Must match Google Console
}, callback);
In Google Developer Console
Authorized redirect URIs:
http://localhost:3000/auth/google/redirect
If these do not match exactly (including trailing slashes), Google will reject the request with a "redirect_uri_mismatch" error.
Common Mistakes
| Mistake | Fix |
|---|---|
| Trailing slash mismatch | Use the exact same URL in both places |
| HTTP vs HTTPS | Use HTTP for localhost, HTTPS for production |
| Wrong port | Include the port number for localhost |
| Not saving in Console | Click Save after adding the URI |
The Callback Route
// routes/auth-routes.js
router.get('/google/redirect', passport.authenticate('google'),
function(req, res) {
// The user has been authenticated
res.send('You reached the callback URI');
}
);
When Google redirects to this route, Passport intercepts the request, extracts the authorization code from the URL, exchanges it for an access token, and fires the callback function.
Key Takeaways
- The Redirect URI must match exactly between your code and Google Console
- Google appends an authorization code to the redirect URL
- Passport automatically extracts the code and exchanges it for a token
- Use
http://localhost:3000for development; update to HTTPS for production