Session Management
Handle user sessions, tokens, and authentication state
getSession()
Retrieve current user session and authentication state
getSession(): Promise<Session | null>
refreshToken()
Manually refresh the access token using refresh token
refreshToken(): Promise<Result>
verifyToken()
Verify the current access token validity
verifyToken(): Promise<Result>
isAuthenticated()
Check if user has valid authentication tokens
isAuthenticated(): boolean
getSession()
The getSession
method retrieves the current user session, automatically handling token refresh if needed. Returns null if no valid session exists.
Basic Usage
import { getSession } from 'easyauth';
// Get current session
const session = await getSession();
if (session) {
console.log('User:', session.user);
console.log('User ID:', session.user.id);
console.log('Email:', session.user.email);
console.log('Username:', session.user.username);
console.log('Role:', session.user.role);
} else {
console.log('No active session');
}
Session Object Structure
// Session object structure
{
user: {
id: "user-uuid",
email: "user@example.com",
username: "username",
role: "user" // or "admin", etc.
},
expires: null // Currently not used
}
refreshToken()
The refreshToken
method manually refreshes the access token using the stored refresh token. This is usually handled automatically by the SDK.
Usage
import { refreshToken } from 'easyauth';
try {
const result = await refreshToken();
if (result.success) {
console.log('Token refreshed successfully');
console.log('New token:', result.token);
} else {
console.error('Token refresh failed:', result.message);
}
} catch (error) {
console.error('Error refreshing token:', error);
}
verifyToken()
The verifyToken
method checks if the current access token is valid with the server.
Usage
import { verifyToken } from 'easyauth';
try {
const result = await verifyToken();
if (result.success) {
console.log('Token is valid');
} else {
console.log('Token is invalid or expired');
}
} catch (error) {
console.error('Token verification failed:', error);
}
isAuthenticated()
The isAuthenticated
method provides a quick, synchronous check for authentication status by looking for stored tokens. This doesn't verify token validity with the server.
Usage
import { isAuthenticated } from 'easyauth';
// Quick check for authentication
if (isAuthenticated()) {
console.log('User has tokens stored');
// Redirect to dashboard or show authenticated content
} else {
console.log('User is not authenticated');
// Redirect to login page
}
// Use in conditional rendering
function App() {
return (
<div>
{isAuthenticated() ? (
<AuthenticatedApp />
) : (
<LoginForm />
)}
</div>
);
}
Token Storage
The EasyAuth SDK automatically manages token storage using secure HTTP-only cookies with proper security settings including SameSite protection and secure flags for HTTPS.
Token Storage Details
// Debug token information
import { debugTokens, getStoredAccessToken, getStoredRefreshToken } from 'easyauth';
// Get debug info
const tokenInfo = debugTokens();
console.log('Has access token:', tokenInfo.hasAccessToken);
console.log('Has refresh token:', tokenInfo.hasRefreshToken);
console.log('Is authenticated:', tokenInfo.isAuthenticated);
// Get raw tokens (use with caution)
const accessToken = getStoredAccessToken();
const refreshToken = getStoredRefreshToken();
Session Events
Listen to session changes throughout your application using the events system.
import { events } from 'easyauth';
// Listen for session changes
const unsubscribe = events.on('session', (session, status) => {
console.log('Session changed:', { session, status });
if (status === 'authenticated') {
console.log('User logged in:', session.user);
} else if (status === 'unauthenticated') {
console.log('User logged out');
} else if (status === 'loading') {
console.log('Session loading...');
}
});
// Clean up listener when component unmounts
return unsubscribe;
Next Steps
Now that you understand session management, explore other SDK features: