Skip to main content

Session Handling

Manage user sessions and authentication state in your application.


Session Overview

SyAuth uses token-based sessions:

  • No server-side session storage required
  • Stateless authentication
  • Tokens stored in secure HttpOnly cookies
  • Automatic session restoration on page load

Session Lifecycle


Checking Session State

Using the SDK

'use client';

import { useSyAuth } from '@syauth/nextjs';

export function SessionStatus() {
const {
isAuthenticated, // Is user logged in?
isLoading, // Is session being restored?
user // User data
} = useSyAuth();

if (isLoading) {
return <p>Checking session...</p>;
}

if (!isAuthenticated) {
return <p>No active session</p>;
}

return (
<div>
<p>Logged in as: {user?.email}</p>
<p>Session active</p>
</div>
);
}

Session Persistence

Page Reload

When the page loads:

  1. SDK checks for existing tokens in cookies
  2. Validates token expiration
  3. Refreshes if needed
  4. Restores user and isAuthenticated state
// On page load, isLoading is true while session is being validated
const { isAuthenticated, isLoading } = useSyAuth();

if (isLoading) {
// Session is being restored
return <LoadingSpinner />;
}

New Tab / Window

Each tab/window shares the same session via cookies:

  • Login in Tab A → Tab B is also logged in
  • Logout in Tab A → Tab B session invalidated (on next action)

Session Timeout

Access Token Expiration

  • Default: 1 hour
  • SDK refreshes automatically before expiration
  • No user interruption

Refresh Token Expiration

  • Default: 30 days (configurable)
  • When expired, user must re-authenticate
  • Graceful redirect to login

Idle Timeout (Optional)

Implement idle timeout in your application:

import { useEffect } from 'react';
import { useSyAuth } from '@syauth/nextjs';

const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes

export function useIdleTimeout() {
const { logout } = useSyAuth();

useEffect(() => {
let timeoutId: NodeJS.Timeout;

const resetTimer = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
logout();
}, IDLE_TIMEOUT);
};

// Reset on user activity
window.addEventListener('mousemove', resetTimer);
window.addEventListener('keydown', resetTimer);

resetTimer();

return () => {
clearTimeout(timeoutId);
window.removeEventListener('mousemove', resetTimer);
window.removeEventListener('keydown', resetTimer);
};
}, [logout]);
}

Ending Sessions

Logout

const { logout } = useSyAuth();

// End session and clear tokens
logout();

Logout All Devices

Use the API to revoke all tokens for a user:

Logout All Devices

To logout from all devices, you must revoke all active refresh tokens for the user. This typically involves invalidating the user's sessions in your own database or using the specific token revocation endpoint for each token.

POST https://api.syauth.com/e/v1/oauth/revoke/
Content-Type: application/x-www-form-urlencoded

token=<token_to_revoke>&token_type_hint=refresh_token

Session Events

Listen to session changes:

import { useSyAuth } from '@syauth/nextjs';
import { useEffect } from 'react';

export function SessionListener() {
const { isAuthenticated, user } = useSyAuth();

useEffect(() => {
if (isAuthenticated) {
console.log('User logged in:', user?.email);
// Track analytics, load user preferences, etc.
} else {
console.log('User logged out');
// Cleanup, redirect, etc.
}
}, [isAuthenticated, user]);

return null;
}

Server-Side Session Validation

In API Routes

// src/app/api/protected/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
const accessToken = request.cookies.get('syauth_access_token')?.value;

if (!accessToken) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

// Validate token with SyAuth
const userInfoResponse = await fetch('https://api.syauth.com/e/v1/oauth/userinfo', {
headers: { 'Authorization': `Bearer ${accessToken}` }
});

if (!userInfoResponse.ok) {
return NextResponse.json({ error: 'Invalid session' }, { status: 401 });
}

const user = await userInfoResponse.json();

// Proceed with authenticated request
return NextResponse.json({ data: 'protected data', user });
}

Cross-Tab Synchronization

Handle session changes across browser tabs:

import { useEffect } from 'react';
import { useSyAuth } from '@syauth/nextjs';

export function CrossTabSync() {
const { checkSession } = useSyAuth();

useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
// Re-check session when tab becomes visible
checkSession();
}
};

document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [checkSession]);

return null;
}

Next Steps