Skip to main content

Overview

The generateSessionToken function creates secure, unique tokens for managing user sessions. These tokens can include user identification, timestamps, and customizable expiration times. Perfect for:
  • User session management
  • Authentication token generation
  • API access tokens
  • Temporary authorization codes
  • Secure session tracking
  • Stateless authentication systems

Function Signature

import { generateSessionToken } from 'validauth';

const token = generateSessionToken(options);

Parameters

options
object
Configuration object for session token generation
length
number
default:"32"
The base length of the random token (excludes timestamp and userID). Minimum recommended: 16 characters.
userID
string
default:"null"
Optional user identifier to append to the token. When provided, the userID is concatenated to the token for easy session-to-user mapping.
expiresIn
string
default:"1h"
Expiration time for the session token. Common values: “15m”, “1h”, “24h”, “7d”. This is metadata that should be stored alongside the token.
includeTimestamp
boolean
default:"true"
Whether to append the current timestamp to the token. Helps with token uniqueness and creation time tracking.
details
boolean
default:"false"
When true, returns an object with detailed information including token metadata. When false, returns only the token string.

Return Value

The return type depends on the details parameter:

Basic Mode (details: false)

token
string
The generated session token string.

Detailed Mode (details: true)

result
object
Detailed information about the generated session token
token
string
The complete generated token string.
userID
string | null
The user ID associated with the token, if provided.
expiresIn
string
The expiration time specification for the token.
length
number
The total length of the generated token (including timestamp and userID if included).
timestamp
number | null
The Unix timestamp when the token was created, if includeTimestamp is true.
errors
string[] | null
Array of error messages if validation failed (e.g., length too short), or null if no errors.

Examples

Basic Usage

Generate a session token with default settings:
import { generateSessionToken } from 'validauth';

const token = generateSessionToken();
console.log(token); // Example: "xK8mP2vN9qR4sT7wY5uZ3aB6cD1eF4gH1710847234567"

With User ID

Generate a token associated with a specific user:
const token = generateSessionToken({
  userID: 'user123'
});
console.log(token);
// Example: "xK8mP2vN9qR4sT7wY5uZ3aB6cD1eF4gH1710847234567user123"

Custom Length and Expiration

Create a longer token with custom expiration:
const token = generateSessionToken({
  length: 64,
  expiresIn: '24h'
});
console.log(token);
// Example: Long 64-character token + timestamp

Without Timestamp

Generate a token without timestamp for simpler format:
const token = generateSessionToken({
  length: 32,
  includeTimestamp: false
});
console.log(token);
// Example: "xK8mP2vN9qR4sT7wY5uZ3aB6cD1eF4gH"

With Detailed Information

Get comprehensive details about the generated token:
const result = generateSessionToken({
  length: 32,
  userID: 'user456',
  expiresIn: '7d',
  includeTimestamp: true,
  details: true
});

console.log(result);
/* Output:
{
  token: "xK8mP2vN9qR4sT7wY5uZ3aB6cD1eF4gH1710847234567user456",
  userID: "user456",
  expiresIn: "7d",
  length: 58,
  timestamp: 1710847234567,
  errors: null
}
*/

Error Handling

Handle validation errors when length is too short:
const result = generateSessionToken({
  length: 8,  // Too short!
  details: true
});

console.log(result);
/* Output:
{
  token: "",
  errors: ["Token length should be at least 16 characters."]
}
*/

Use Cases

User Login Session

Create a session token after successful login:
function createUserSession(userId) {
  const sessionData = generateSessionToken({
    length: 48,
    userID: userId,
    expiresIn: '24h',
    includeTimestamp: true,
    details: true
  });
  
  // Store session in database or cache
  storeSession({
    token: sessionData.token,
    userId: sessionData.userID,
    createdAt: sessionData.timestamp,
    expiresAt: Date.now() + 24 * 60 * 60 * 1000 // 24 hours
  });
  
  return sessionData.token;
}

API Access Token

Generate long-lived API tokens:
function generateAPIToken(apiKeyId) {
  const token = generateSessionToken({
    length: 64,
    userID: apiKeyId,
    expiresIn: '90d',
    includeTimestamp: true
  });
  
  // Store hashed version
  const hashedToken = hashToken(token);
  storeAPIKey(apiKeyId, hashedToken);
  
  // Return token only once
  return token;
}

Temporary Access Code

Create short-lived access tokens:
function createTempAccess(resourceId, userId) {
  const token = generateSessionToken({
    length: 32,
    userID: `${userId}:${resourceId}`,
    expiresIn: '15m',
    includeTimestamp: true,
    details: true
  });
  
  // Store with short expiration
  storeTempAccess({
    token: token.token,
    userId,
    resourceId,
    expiresAt: Date.now() + 15 * 60 * 1000
  });
  
  return token.token;
}

Session Refresh

Implement token refresh mechanism:
function refreshSession(oldToken) {
  const session = getSession(oldToken);
  
  if (!session || isExpired(session)) {
    return { error: 'Invalid or expired session' };
  }
  
  // Generate new token
  const newToken = generateSessionToken({
    length: 48,
    userID: session.userId,
    expiresIn: '24h',
    includeTimestamp: true
  });
  
  // Invalidate old token
  deleteSession(oldToken);
  
  // Store new token
  createUserSession(session.userId);
  
  return { token: newToken };
}

Multi-Device Sessions

Manage sessions across multiple devices:
function createDeviceSession(userId, deviceId) {
  const token = generateSessionToken({
    length: 48,
    userID: `${userId}:${deviceId}`,
    expiresIn: '30d',
    includeTimestamp: true,
    details: true
  });
  
  // Store device-specific session
  storeDeviceSession({
    token: token.token,
    userId,
    deviceId,
    createdAt: token.timestamp,
    lastActive: Date.now(),
    expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000
  });
  
  return token.token;
}

function listUserSessions(userId) {
  return getAllSessionsByUser(userId);
}

function revokeDeviceSession(userId, deviceId) {
  return deleteDeviceSession(userId, deviceId);
}

Security Considerations

Critical Security Notes:
  • Tokens use Math.random() which is not cryptographically secure. For production systems, consider using crypto.randomBytes() or similar
  • Always transmit tokens over HTTPS
  • Store tokens hashed in your database
  • Never log tokens in production
  • Implement token rotation for long-lived sessions
  • Use short expiration times when possible
Best Practices:
  • Use at least 32 characters for base token length
  • Always include timestamps for uniqueness
  • Implement token refresh mechanisms
  • Set appropriate expiration times based on use case
  • Use different tokens for different purposes (session vs API)
  • Implement token revocation functionality
  • Monitor and log token usage patterns
  • Consider using JWT for stateless authentication

Token Length Recommendations

Use CaseRecommended LengthExpiration
Web Session48-64 characters24 hours
Mobile Session48-64 characters30 days
API Token64+ characters90 days
Temporary Access32 characters15 minutes
Remember Me64 characters30 days

Token Structure

The generated token follows this structure:
[random_chars][timestamp][userID]
  • random_chars: Random alphanumeric string of specified length
  • timestamp: Unix timestamp (if includeTimestamp is true)
  • userID: User identifier (if provided)

Example Breakdown

const token = generateSessionToken({
  length: 16,
  userID: 'user123',
  includeTimestamp: true
});
// Result: "xK8mP2vN9qR4sT7w1710847234567user123"
//         └─ 16 chars ──┘└─ timestamp ─┘└─ userID ─┘

Character Set

The generator uses alphanumeric characters for the random portion:
  • Characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Integration with Validators

Combine with the session token validator for complete session management:
import { generateSessionToken, validateSessionToken } from 'validauth';

function createAndValidateSession(userId) {
  // Generate token
  const tokenData = generateSessionToken({
    length: 48,
    userID: userId,
    expiresIn: '24h',
    includeTimestamp: true,
    details: true
  });
  
  // Validate format
  const validation = validateSessionToken(tokenData.token, {
    minLength: 48,
    details: true
  });
  
  if (!validation.valid) {
    throw new Error('Generated token failed validation');
  }
  
  // Store session
  storeSession({
    token: hashToken(tokenData.token),
    userId,
    expiresAt: Date.now() + 24 * 60 * 60 * 1000
  });
  
  return tokenData.token;
}

function verifySessionToken(token) {
  // Validate format first
  const validation = validateSessionToken(token, {
    minLength: 48,
    details: true
  });
  
  if (!validation.valid) {
    return { valid: false, error: 'Invalid token format' };
  }
  
  // Check against stored sessions
  const session = getSessionByToken(hashToken(token));
  
  if (!session || Date.now() > session.expiresAt) {
    return { valid: false, error: 'Session expired' };
  }
  
  return { valid: true, userId: session.userId };
}

Expiration Time Formats

Common expiration time specifications:
  • "15m" - 15 minutes
  • "1h" - 1 hour
  • "24h" - 24 hours
  • "7d" - 7 days
  • "30d" - 30 days
  • "90d" - 90 days
The expiresIn parameter is metadata only. You must implement actual expiration logic in your application by storing the expiration timestamp and checking it during validation.

Build docs developers (and LLMs) love