Svelte: Maintaining Google Drive API authentication after page refresh

Hi everyone! I’m working on a Svelte project that uses the Google Drive API. Everything works great after signing in, but I’m stuck on keeping the user authenticated after refreshing the page.

I’ve tried using refreshToken, but it returns undefined. I’m not sure how to implement the access_type: 'offline' option either.

Here’s a simplified version of my setup:

function initAuth() {
  gapi.load('client', async () => {
    await gapi.client.init({
      apiKey: 'MY_API_KEY',
      discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
    });
    
    const tokenClient = google.accounts.oauth2.initTokenClient({
      client_id: 'MY_CLIENT_ID',
      scope: 'https://www.googleapis.com/auth/drive',
      callback: handleAuthResponse
    });
    
    tokenClient.requestAccessToken({ prompt: 'consent' });
  });
}

function handleAuthResponse(response) {
  if (response.error) {
    console.error('Auth error:', response.error);
    return;
  }
  
  const token = gapi.client.getToken();
  localStorage.setItem('accessToken', token.access_token);
  // How to get and store refresh token?
}

function uploadFile() {
  // Use stored access token for API requests
  const accessToken = localStorage.getItem('accessToken');
  // API request code here
}

// How to refresh the token when it expires?

Any ideas on how to maintain authentication across page reloads? Thanks!

In my experience, maintaining Google Drive API authentication across page refreshes in Svelte requires a combination of server-side and client-side strategies. Instead of relying solely on client-side storage, I’ve found success implementing a session-based approach on the server.

Consider setting up an Express.js server to handle authentication. Store the tokens securely in server-side sessions using libraries like express-session. On the client, make an API call to your server to check the session status on page load.

This method enhances security by keeping sensitive tokens off the client and provides a smoother user experience. It’s also worth implementing token refresh logic on the server to handle expirations transparently.

Remember to use HTTPS in production to protect the communication between your Svelte app and the server. This approach has proven robust in my projects, effectively maintaining authentication state across refreshes.

yea, i had the same problem. what worked for me was using a session storage instead of local storage. it keeps the token while the browser is open, even after refresh. just change ur code to use sessionStorage.setItem and sessionStorage.getItem. also, make sure ur handling token expiration properly. hope this helps!

I’ve dealt with a similar issue in my Svelte project using the Google Drive API. The key is to request offline access when initializing the token client. Here’s what worked for me:

In the initTokenClient call, add access_type: ‘offline’ to the options:

const tokenClient = google.accounts.oauth2.initTokenClient({
  client_id: 'MY_CLIENT_ID',
  scope: 'https://www.googleapis.com/auth/drive',
  access_type: 'offline',
  callback: handleAuthResponse
});

This should give you a refresh token in the response. Store both the access token and refresh token:

function handleAuthResponse(response) {
  if (response.error) return;
  
  const token = gapi.client.getToken();
  localStorage.setItem('accessToken', token.access_token);
  localStorage.setItem('refreshToken', token.refresh_token);
}

Then, implement a function to refresh the token when needed:

async function refreshAccessToken() {
  const refreshToken = localStorage.getItem('refreshToken');
  // Use your server to exchange the refresh token for a new access token
  // Store the new access token in localStorage
}

Call this function before making API requests if the access token is expired. This approach has kept my users authenticated even after page refreshes.