#Custom lifetime for convex auth

1 messages · Page 1 of 1 (latest)

silver latchBOT
#

Hi @wet leaf. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can customize the lifetime of sessions in Convex Auth. There are two main duration settings you can configure:

  1. JWT Duration: Controls how long the JWT token is valid before it needs to be refreshed.
  2. Session Duration: Controls how long the session can exist in total.

Here's how you can configure these settings:

export const { auth, signIn, signOut, store } = convexAuth({
  providers: [/* your providers */],
  jwt: {
    durationMs: 1000 * 60 * 60 * 24 /* 1 day */,
  },
  session: {
    inactiveDurationMs: 1000 * 60 * 60 * 24 /* 1 day */,
    totalDurationMs: 1000 * 60 * 60 * 24 * 7 /* 7 days */,
  },
});

The jwt.durationMs setting determines how long the JWT token is valid before it needs to be refreshed. The session.inactiveDurationMs setting determines how long a session can be inactive before it's considered expired, and session.totalDurationMs sets the maximum lifetime of a session regardless of activity.

These settings are documented in the Convex Auth API reference Session documentation.

Note that the durations are specified in milliseconds, so make sure to convert your desired timeframes accordingly. In the example above, I've set the JWT duration and inactivity timeout to 1 day, and the maximum session lifetime to 7 days.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

Will this refresh the jwt token every time i use the app so that it will last longer? @silver latch

silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Yes, the Convex client will automatically refresh the JWT token before it expires as long as the user is actively using your app. This behavior helps maintain a seamless user experience without requiring manual re-authentication.

The Convex client is designed to proactively fetch a new token a few seconds before the current one expires. By default, it refreshes the token 2 seconds before expiration, but you can customize this with the authRefreshTokenLeewaySeconds option when initializing your client:

const convex = new ConvexReactClient(process.env.CONVEX_URL, {
  authRefreshTokenLeewaySeconds: 60 // refresh 1 minute before expiration
});

This automatic refresh mechanism means that as long as:

  1. The user is actively using your app
  2. The total session duration hasn't been exceeded
  3. The inactivity timeout hasn't been triggered

...the user will remain authenticated without interruption, even if they use the app for longer than the JWT duration you've set.

It's worth noting that if the app is left in the background for an extended period and then brought back to the foreground after the token has expired, there can sometimes be authentication issues. The Convex team is actively working on improving this specific scenario as mentioned in their Discord support threads.

If your goal is to keep users signed in indefinitely (like social media apps), you should set appropriate values for both the JWT duration and session parameters to balance security and user experience.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

@silver latch What would happen in this example:

  1. The user logs in to the app uses it for 15 minutes and close the browser
  2. 15 hours later they go back to my website (will they still be logged in?) and close the browser
  3. 15 hours later (30 hours after the original login) they go back to my website. will they now be logged out, or will the token have been refreshed in the second session?
silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on your scenario and the Convex Auth configuration you mentioned earlier (JWT duration of 1 day and session inactivity timeout of 1 day), here's what would happen:

  1. After the user logs in and uses the app for 15 minutes, then closes the browser:
    The session is established and the JWT token is valid.

  2. When they return 15 hours later:
    They would still be logged in because both the JWT token (valid for 24 hours) and the session inactivity timeout (also 24 hours) haven't expired yet. During this visit, the JWT token would be refreshed automatically since they're actively using the app.

  3. When they return 30 hours after the original login:
    They would still be logged in. This is because even though 30 hours have passed since the original login, their second visit at the 15-hour mark refreshed both the session activity timestamp and the JWT token. The inactivity period is only 15 hours (from their second visit to their third visit), which is less than the 24-hour inactivity timeout.

However, there are some important caveats to be aware of:

  1. Browser behavior: By default, browsers typically store authentication data in session storage which gets cleared when the browser is closed. To maintain login state between browser sessions, you need to ensure you're using persistent storage like cookies or localStorage.

  2. Session cookies vs. persistent cookies: If you're using cookies for authentication, the default behavior in some frameworks is to use "session cookies" that expire when the browser closes. You may need to configure cookie expiration explicitly as mentioned in Discord support.

#
  1. Background token refresh issues: There have been reported issues with token refreshing when apps are left in the background for extended periods, which the Convex team is actively working on as noted in Discord discussions.

For the most reliable persistent authentication experience, you should:

  • Ensure you're using persistent storage for auth tokens
  • Set appropriate JWT and session durations
  • Consider implementing additional refresh mechanisms for critical applications

If you need users to stay logged in for very long periods, you might want to increase both the JWT duration and session timeouts beyond the 1-day setting you mentioned.

Hope this helps clarify the expected behavior in your scenario!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

@silver latch do i need to keep the same length for the jwt duration and inactiveduratoin?

silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

No, you don't need to keep the same length for the JWT duration and inactivity duration. These are separate configuration options that serve different purposes in Convex Auth:

  1. JWT Duration (jwt.durationMs): Controls how long the JWT token is valid before it needs to be refreshed. This is about the token itself.

  2. Session Inactivity Duration (session.inactiveDurationMs): Controls how long a session can be inactive before it's considered expired.

You can set these to different values based on your security and user experience requirements. For example, you might want a shorter JWT duration (like 1 hour) for security reasons, while allowing a longer inactivity period (like 24 hours) to provide a better user experience.

Here's an example configuration with different durations:

export const { auth, signIn, signOut, store } = convexAuth({
  providers: [/* your providers */],
  jwt: {
    durationMs: 1000 * 60 * 60 /* 1 hour */,
  },
  session: {
    inactiveDurationMs: 1000 * 60 * 60 * 24 /* 24 hours */,
    totalDurationMs: 1000 * 60 * 60 * 24 * 7 /* 7 days */,
  },
});

With this configuration, as long as the user is active, the JWT will be automatically refreshed before it expires (typically a few seconds before). The session will remain valid as long as the user doesn't stay inactive for more than 24 hours and the total session duration doesn't exceed 7 days.

The Convex team is actively working on improving token refresh mechanisms, particularly for cases when apps are left in the background for extended periods as noted in Discord discussions.

#

I'm here to help if you have any other questions about configuring Convex Auth!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

@silver latch what are the default values?

silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on the knowledge sources, here are the default values for Convex Auth session and JWT durations:

  1. JWT Duration (jwt.durationMs):

    • Default: 1 hour (3,600,000 milliseconds)
  2. Session Total Duration (session.totalDurationMs):

    • Default: 30 days
  3. Session Inactivity Duration (session.inactiveDurationMs):

    • Default: 30 days

These defaults are documented in the Convex Auth API reference Auth API Reference.

It's worth noting that in one of the Discord support threads, there was confusion about the duration units - they are in milliseconds, not seconds. So when configuring these values, make sure to convert your desired timeframes accordingly (e.g., 1000 * 60 * 60 for 1 hour).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

@silver latch

this is my current setup. why is it showing loading for the sign out button if i am using jwt?

silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on the information in your question, it seems you're experiencing an issue where your sign-out button is stuck in a loading state when using JWT authentication with Convex. Without seeing your specific code implementation, I'll explain some common causes and solutions for this issue based on the knowledge sources.

The issue you're experiencing might be related to how authentication state is handled in Convex. When using components like <Authenticated>, <Unauthenticated>, and <AuthLoading> from Convex, there are a few important things to understand:

  1. Authentication State Management: The useConvexAuth() hook provides isLoading and isAuthenticated states that determine which components are displayed. If you're seeing the loading state persistently, there might be an issue with how these states are being updated.

  2. Sign-Out Behavior: By default, Convex's signOut() function doesn't automatically redirect users or update UI state immediately. As mentioned in a Discord support thread:

    "Yep it's not meant to redirect -- just to sign you out. Something like what you described (signOut().then(() => router.push("/signin")) sounds good." Discord support thread

  3. Race Conditions: There could be race conditions between authentication state updates:

    "If I'm doing the same things you are, this sounds like it could be a race condition (also what you said above, that if you added delays it was fine) so the goal is avoiding ever making an authed query before loading" Discord support thread

Here are some potential solutions:

  1. Check your implementation of authentication components:
    Make sure you're using the components correctly. For example:
#
   <AuthLoading>Loading...</AuthLoading>
   <Authenticated>
     <button onClick={() => void signOut()}>Sign out</button>
   </Authenticated>
   <Unauthenticated>
     <button onClick={() => void signIn("provider")}>Sign in</button>
   </Unauthenticated>
  1. Ensure HTTP routes are properly configured:
    One community member found that they needed to add auth.addHttpRoutes(http); to their http.ts file:

    "Update: I found the issue, I needed to add auth.addHttpRoutes(http); to my http.ts" Discord support thread

  2. Handle sign-out with manual UI updates:
    You might need to manually handle UI updates after sign-out:

    const handleSignOut = () => {
      signOut().then(() => {
        // Optionally redirect or update UI state
        router.push("/signin");
        // or
        window.location.reload(false);
      });
    };
    

Without seeing your specific implementation, it's difficult to pinpoint the exact cause. If you could share your authentication setup code, particularly how you're implementing the sign-out functionality and the components around it, I could provide more targeted assistance.

Is there any specific part of your authentication flow that you'd like me to explain in more detail?

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@wet leaf Kapa.ai is still learning and improving, please let me know how I did by reacting below.

wet leaf
#

@silver latch
import GitHub from "@auth/core/providers/github";
import { convexAuth } from "@convex-dev/auth/server";

export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
providers: [GitHub],
});
this is my current auth.ts

silver latchBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

I see your current auth.ts file is set up with GitHub as your authentication provider using Convex Auth. This looks like a standard basic configuration for Convex Auth with GitHub OAuth.

Based on your previous question about the sign-out button showing "loading", I notice that your configuration doesn't include any custom JWT or session duration settings. This means you're using the default values:

  • JWT Duration: 1 hour
  • Session Inactivity Duration: 30 days
  • Session Total Duration: 30 days

Your configuration is correctly exporting all the necessary functions, including isAuthenticated, which is important. Some users have reported issues when they forgot to export isAuthenticated from their convexAuth configuration:

"Yea, probably the issue is due to missing isAuthenticated from your export there" Discord support thread

For the loading issue you mentioned earlier, this basic configuration looks correct. The issue might be in how you're implementing the authentication UI components or HTTP routes in your application.

To troubleshoot the loading issue, make sure:

  1. You've added auth.addHttpRoutes(http); to your http.ts file
  2. Your GitHub OAuth configuration is properly set up with the correct callback URL
  3. You're correctly using the <Authenticated>, <Unauthenticated>, and <AuthLoading> components

If you'd like to customize the JWT or session durations as we discussed earlier, you could modify your configuration like this:

export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
  providers: [GitHub],
  jwt: {
    durationMs: 1000 * 60 * 60 * 24 /* 1 day */,
  },
  session: {
    inactiveDurationMs: 1000 * 60 * 60 * 24 /* 1 day */,
    totalDurationMs: 1000 * 60 * 60 * 24 * 7 /* 7 days */,
  },
});
#

Would you like me to help troubleshoot the loading issue further or explain any other aspect of the Convex Auth configuration?

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: