Refresh Token
How Light-Auth automatically refreshes access tokens.
Light-Auth includes a built-in mechanism to automatically refresh OAuth access tokens when they are nearing expiration. This process happens transparently in the background, ensuring your users remain authenticated without interruption.
It helps maintain continuous user sessions and prevents abrupt authentication failures.
How Token Refresh Works
Token Refresh Process
When getUser()
is called, Light-Auth checks the expiration time of the current access token.
If the token is set to expire within approximately 10 minutes, Light-Auth initiates a refresh process.
Using the refresh token (if available), Light-Auth makes a request to the OAuth provider to obtain a new access token.
If the token is set to expire within approximately 10 minutes, Light-Auth initiates a refresh process.
This process is completely transparent to the user, who remains authenticated without interruption.
Enabling Token Refresh
Configuring your providers to support offline access for token refresh
For automatic token refresh to work, your OAuth providers must be configured to support "offline access" or explicitly provide refresh tokens. Here's how to configure various providers:
Google OAuth Configuration
To enable offline access for Google, add the access_type=offline
parameter to your authorization request:
import { Google } from "arctic";
import { LightAuthProvider } from "@light-auth/core";
const googleProvider: LightAuthProvider = {
providerName: "google",
artic: new Google(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
"http://localhost:3000/api/auth/callback/google"
),
// This parameter is crucial for receiving refresh tokens
searchParams: new Map([["access_type", "offline"]])
};
Google only provides a refresh token on the first authorization unless you include the prompt=consent
parameter, which forces the consent screen to appear each time.
Token Refresh Mechanics
Understanding when and how Light-Auth performs token refresh
When Token Refresh Occurs
Light-Auth checks the expiration time of the access token every time the getUser()
method is called. If the token is set to expire within approximately 10 minutes, Light-Auth will automatically attempt to refresh it.
// Example: This will trigger a token check and potential refresh
import { getUser } from "@/lib/auth";
export async function ProfilePage() {
// If the access token is expiring soon, it will be refreshed before
// the user data is returned
const user = await getUser();
return (
<div>
<h1>Welcome, {user.name}</h1>
{/* ... */}
</div>
);
}
Refresh Logic Flow
Light-Auth follows this process when checking and refreshing tokens:
- Check if the current user payload contains an access token
- Gets the access token expiration time
- If the token expires in less than 10 minutes, check if a refresh token is available
- If a refresh token exists, make a request to the OAuth provider's token endpoint to get a new access token
- Update the user payload with the new access token and refresh token (if provided)
- Save the new user payload in the data store using the
UserAdapter
configured - Continue with the original request using the new access token
Troubleshooting Token Refresh
Common issues and solutions for token refresh problems
If you're experiencing issues with token refresh, here are some common problems and solutions:
Refresh Token Not Being Provided
If your provider isn't returning refresh tokens:
- Ensure you've configured the provider with the correct parameters for offline access
- Check if the provider requires additional scopes or permissions for refresh tokens
- Some providers (like Google) only send a refresh token on the first authentication unless forced to show the consent screen again
Token Refresh Failing
If the token refresh process is failing:
- Verify that your client secrets and IDs are correct
- Check if the refresh token has expired (some providers have expiring refresh tokens)
- Ensure your application has the necessary permissions in the provider's developer console
- Look for error messages in your server logs that might provide more details about the failure
Users Logged Out Unexpectedly
If users are being logged out when they shouldn't be:
- Check that your session configuration doesn't have a too-short expiration time
- Verify that your application calls
getUser()
regularly enough to trigger refreshes - Ensure that cookies are being properly stored and sent with requests (check for SameSite, Secure, or other cookie policy issues)
Best Practices for Token Refresh
Recommendations for optimal token refresh implementation
Optimizing Token Refresh in Your Application
Use getUser()
Strategically.
getUser()
at key points in your application where fresh authentication is important, such as before making critical API requests.Implement Error Handling
Configure Session Timeouts Appropriately
Respect Provider Limitations
Light-Auth's Automatic Advantage
One of Light-Auth's key benefits is that token refresh happens automatically without requiring any special code in your application. Just ensure your providers are configured for offline access, and Light-Auth will handle the rest.