W
Wasp•2mo ago
Joaquim

Check if user has auth token

Hey! What's the best way to check if the user has an auth token? I don't want for useAuth to resolve before redirecting to the landing page if the user is logged out. If my server is lagging or broken, I would rather logged out people to be immediately redirected to the landing than waiting on a loading screen. I was thinking that I can check if the client has the local storage var wasp:sessionId set. If not, I immediately redirect to the landing. Does this make sense? Should I be worried about this var name being changed in the future?
2 Replies
kapa.ai
kapa.ai•2mo ago
Hi @Joaquim. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Your approach of checking for the presence of the wasp:sessionId in localStorage is a reasonable way to quickly determine if a user might be logged in, but there are a few important considerations to keep in mind: 1. Wasp uses sessions stored in localStorage for authentication, as mentioned in the Auth Overview documentation (https://wasp-lang.dev/docs/auth/overview#sessions). This confirms that checking localStorage is a valid approach. 2. However, relying solely on the presence of wasp:sessionId in localStorage doesn't guarantee that the session is still valid on the server side. It's possible for the session to be expired or invalidated on the server while still present in localStorage. 3. The useAuth hook is the recommended way to check authentication status in Wasp, as it provides the most up-to-date information about the user's auth state. Using the useAuth hook documentation (https://wasp-lang.dev/docs/auth/overview#using-the-useauth-hook) 4. Regarding the specific localStorage key name wasp:sessionId, there's no guarantee that this name won't change in future versions of Wasp. The internal implementation details of how Wasp stores session information could potentially change. Given these considerations, here's a suggested approach: 1. Use the useAuth hook as the primary method for checking authentication status. 2. For a quick initial check, you can look for the presence of wasp:sessionId in localStorage, but treat this as a preliminary check only. 3. Implement a fallback mechanism where you redirect to the landing page if the useAuth hook takes too long to resolve or if there's an error. Here's a basic example of how you might implement this:
import { useAuth } from 'wasp/client/auth'
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'
function AuthenticatedComponent() {
const { data: user, isLoading, error } = useAuth()
const history = useHistory()

useEffect(() => {
const sessionId = localStorage.getItem('wasp:sessionId')
if (!sessionId) {
// Immediately redirect if no session ID in localStorage
history.push('/landing')
}
}, [])

useEffect(() => {
if (!isLoading && !user) {
// Redirect if useAuth resolves and user is not authenticated
history.push('/landing')
}
}, [isLoading, user])

if (isLoading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>

// Render authenticated content
return <div>Welcome, {user.username}!</div>
}
import { useAuth } from 'wasp/client/auth'
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'
function AuthenticatedComponent() {
const { data: user, isLoading, error } = useAuth()
const history = useHistory()

useEffect(() => {
const sessionId = localStorage.getItem('wasp:sessionId')
if (!sessionId) {
// Immediately redirect if no session ID in localStorage
history.push('/landing')
}
}, [])

useEffect(() => {
if (!isLoading && !user) {
// Redirect if useAuth resolves and user is not authenticated
history.push('/landing')
}
}, [isLoading, user])

if (isLoading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>

// Render authenticated content
return <div>Welcome, {user.username}!</div>
}
This approach gives you a quick initial check using localStorage while still relying on useAuth for the definitive authentication status. Remember that this is a client-side check and should be complemented by proper server-side authentication checks for sensitive operations or data access. As for worrying about the localStorage key name changing in the future, it's a valid concern. To mitigate this, you could consider creating a small utility function that encapsulates the localStorage check. This way, if the key name changes in a future Wasp update, you'd only need to update it in one place in your code. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Joaquim, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
miho
miho•2mo ago
If the session ID is present in the localStorage that means that the current user maybe logged in because until the server says yes that session ID might be invalid. If the session ID is not present in localStorage - that would mean that the user is definitely not logged in. The wasp:sessionId is an internal detail of Wasp framework that might change at any time, but we don't change it that often. You could use the internal fn getSessionId from wasp/client/api. Again, it might change at any point. We might even switch to using cookies and not localStoage in the future. But I guess, you'd update your app then 🙂

Did you find this page helpful?