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.

Automatic token refresh is a key feature that distinguishes Light-Auth from simpler authentication solutions.
It helps maintain continuous user sessions and prevents abrupt authentication failures.

How Token Refresh Works

Token Refresh Process

1

When getUser() is called, Light-Auth checks the expiration time of the current access token.

2

If the token is set to expire within approximately 10 minutes, Light-Auth initiates a refresh process.

3

Using the refresh token (if available), Light-Auth makes a request to the OAuth provider to obtain a new access token.

4

If the token is set to expire within approximately 10 minutes, Light-Auth initiates a refresh process.

5

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:

  1. Check if the current user payload contains an access token
  2. Gets the access token expiration time
  3. If the token expires in less than 10 minutes, check if a refresh token is available
  4. If a refresh token exists, make a request to the OAuth provider's token endpoint to get a new access token
  5. Update the user payload with the new access token and refresh token (if provided)
  6. Save the new user payload in the data store using the UserAdapter configured
  7. 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.

Call getUser() at key points in your application where fresh authentication is important, such as before making critical API requests.

Implement Error Handling

Add proper error handling for cases where token refresh might fail, providing users with a graceful way to re-authenticate.

Configure Session Timeouts Appropriately

Set session timeouts based on your application's security requirements. Longer sessions are more convenient for users but might pose additional security considerations.

Respect Provider Limitations

Be aware that different providers have different refresh token behaviors and limitations. Some have expiring refresh tokens, while others might revoke them after a period of inactivity.

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.