Redirect URIs and Callback Handling
What you'll learn: How OAuth providers send authorization codes back to your application through redirect URIs and how to handle them securely.
The Redirect URI Concept
When a user completes OAuth authorization on a provider's site (like "Sign in with Google"), they need to get back to your application. The redirect URI (also called callback URL) is the exact address where the OAuth provider will send the user—along with an authorization code you'll exchange for tokens.
Think of it like giving someone your return address before they mail you something important. If the address is wrong or unrecognized, the package (authorization code) never arrives.
Configuring Redirect URIs
You must register your redirect URIs with the OAuth provider beforehand:
Registered in OAuth provider dashboard:
https://yourapp.com/auth/callback
http://localhost:3000/auth/callback (for development)
The provider validates that incoming redirect requests match exactly—including protocol (https), domain, port, and path. A mismatch blocks the authorization.
Handling the Callback
When the user returns to your redirect URI, the OAuth provider appends query parameters:
https://yourapp.com/auth/callback?code=ABC123&state=xyz789
Your callback handler must:
- Extract the authorization code from the
codeparameter - Verify the
stateparameter matches what you sent (prevents CSRF attacks—you learned about this in session management) - Exchange the code for tokens by making a server-side request to the provider's token endpoint
- Handle errors if the user denied permission (
?error=access_denied)
Never expose this code exchange in frontend JavaScript—it requires your client secret, which must stay server-side.
Key Takeaway: Redirect URIs are the secure "return address" for OAuth flows; always register them exactly, validate the state parameter, and handle code extraction server-side to prevent security vulnerabilities.