Skip to main content

Token Management

Token management is a critical aspect of working with Nexla's authentication system. Understanding how to handle token lifecycle, refresh mechanisms, and expiration will help you build robust, production-ready applications.

About Token Management

Token management is essential for building reliable applications that maintain continuous access to the Nexla API. Understanding these concepts helps you implement robust authentication handling in your applications.

Token management encompasses several key areas that work together to ensure reliable authentication:

  • Token Lifecycle: Creation, usage, expiration, and refresh
  • Automatic Refresh: Implementing token refresh for long-running processes
  • Expiration Handling: Managing token expiration gracefully
  • Error Recovery: Handling authentication failures and token issues

Token Lifecycle

Understanding the complete lifecycle of tokens helps you implement proper token management throughout your application. This section covers each stage from creation to expiration.

Token Creation

To create tokens, you must authenticate with Nexla using one of the available methods. The authentication process follows a secure series of steps to generate and deliver your access token:

  1. Initial Authentication: Login via UI, CLI, or service key
  2. Token Generation: Nexla generates a unique access token
  3. Response: Nexla returns the token with expiration information
  4. Storage: Store the token securely for future use

Token Usage

Once obtained, tokens serve as your authentication credentials for all Nexla API interactions. Understanding how to properly use tokens ensures secure and reliable access to the platform's resources.

Usage requirements:

  • Include the token in the Authorization header of every API request
  • Use the Bearer authentication scheme
  • Maintain proper token security throughout your application

API request example:

Using Access Token
curl https://api.nexla.io/teams                      \
-H "Authorization: Bearer <access-token>" \
-H "Accept: application/vnd.nexla.api.v1+json"

Token Expiration

All session tokens have a finite lifespan with specific characteristics that affect how you handle them. Understanding expiration behavior is crucial for building reliable applications that maintain continuous access to the Nexla API.

Expiration characteristics:

  • Default Duration: Typically 1 hour (3600 seconds)
  • Configurable: Organizations can set custom expiration times
  • No Warning: Tokens expire without advance notification
  • Immediate Failure: Expired tokens cause 401 Unauthorized errors

Token Expiration

Token expiration is a critical aspect of security that requires careful handling to maintain uninterrupted service. This section explains how to detect and handle token expiration gracefully.

Understanding Expiration

Session access tokens expire after a configurable interval specified in the expires_in attribute of the token response. This time is typically one hour, but may vary based on your organization's security policies. Understanding how expiration works helps you implement proper token lifecycle management and avoid authentication failures.

Key expiration concepts:

  • Security mechanism: Expiration limits the window of opportunity for token misuse
  • Configurable duration: Organizations can set custom expiration times based on security requirements
  • No grace period: Tokens become immediately invalid upon expiration
  • Predictable behavior: Expiration timing is consistent and calculable

Expiration Indicators

The token response includes expiration information that you can use to track and manage token lifecycle. These indicators provide the data needed to implement proactive token refresh and expiration handling in your applications.

Response fields for expiration tracking:

The token response contains specific fields that provide expiration information. Understanding these fields helps you implement proper token lifecycle management and calculate when tokens will expire.

Token Response with Expiration
{
"access_token": "<access-token>",
"token_type": "Bearer",
"expires_in": 3600,
"user": { ... },
"org": { ... }
}

Key expiration fields:

  • expires_in: Seconds until token expiration
  • created_at: Timestamp when token was issued (if provided)
  • expires_at: Calculated expiration timestamp

Handling Expiration

When tokens expire, API requests fail with HTTP status 401 (Unauthorized). Proper expiration handling ensures your application can recover gracefully and maintain continuous operation. Implementing robust expiration handling prevents service interruptions and improves user experience.

Expiration response handling:

When a token expires, your application must follow a systematic approach to recover and maintain service continuity. This process ensures minimal disruption and maintains a seamless user experience.

  1. Detect the Error: Handle 401 responses appropriately
  2. Obtain New Token: Re-authenticate to get a fresh token
  3. Retry Request: Re-attempt the failed API call
  4. Update Storage: Store the new token for future use

Token Refresh

Implementing token refresh mechanisms ensures your applications maintain continuous access to the Nexla API without interruption. This section covers when and how to refresh tokens effectively.

When to Refresh

Refresh tokens before they expire to maintain continuous operation. Proactive token refresh prevents authentication failures and ensures uninterrupted API access. Understanding when to refresh helps you implement optimal refresh strategies for different application scenarios.

Refresh timing considerations:

  • Long-Running Processes: Automated workflows and batch jobs
  • User Sessions: Extended browser sessions
  • Production Systems: Services that need continuous availability
  • Preventive Maintenance: Avoid expiration-related failures

Refresh Process

To refresh an access token, make a POST request to the /token/refresh endpoint. The refresh process is straightforward and follows the same authentication patterns as other API requests. Understanding the refresh process helps you implement reliable token renewal mechanisms.

Refresh request requirements:

  • Valid token: The current token must still be valid (not expired)
  • Proper headers: Include the current token in the Authorization header
  • Empty body: The request body should be empty (Content-Length: 0)

API request example:

Token Refresh Request
curl -X POST <nexla-api-endpoint>/token/refresh      \
-H "Authorization: Bearer <session-access-token>" \
-H "Accept: application/vnd.nexla.api.v1+json" \
-H "Content-Length: 0"

Refresh Response

The refresh response includes a new access token with a reset expiration period. The response format is identical to the initial token response, providing a fresh token with a new expiration timeline. Understanding the refresh response helps you properly handle the new token and update your application state.

Response characteristics:

  • New token: A completely new access token is generated
  • Reset expiration: The expiration timer starts fresh from the refresh time
  • Same format: Response structure matches the initial token response
  • User context: User and organization information remains consistent
Token Refresh Response
{
"access_token": "<new-session-access-token>",
"token_type": "Bearer",
"expires_in": 3600,
"user": {
"id": 12345,
"email": "user@example.com",
"full_name": "Example User",
"api_key": "<user-api-key>",
"super_user": false,
"impersonated": false
},
"org": {
"id": 9876,
"name": "Example Organization"
}
}

Automatic Refresh Implementation

Implement automatic token refresh to handle long-running processes. Automatic refresh eliminates the need for manual token management and ensures your applications maintain continuous access to the Nexla API. This approach is essential for production systems, background jobs, and user sessions that extend beyond token expiration times.

Implementation benefits:

  • Seamless operation: No interruption to API access
  • Reduced complexity: Eliminates manual token refresh handling
  • Improved reliability: Prevents authentication failures
  • Better user experience: Users don't experience authentication timeouts

Key implementation considerations:

  • Refresh timing: Refresh tokens before they expire (typically 5-10 minutes before)
  • Error handling: Implement retry logic for refresh failures
  • State management: Properly update stored tokens after refresh
  • Concurrency: Handle multiple simultaneous refresh attempts

The following examples demonstrate how to implement automatic token refresh in different programming languages. These implementations handle token lifecycle management, expiration detection, and automatic refresh to ensure continuous API access.

Python implementation example:

Python Automatic Token Refresh
import requests
import time
from datetime import datetime, timedelta

class NexlaClient:
def __init__(self, base_url, service_key):
self.base_url = base_url
self.service_key = service_key
self.access_token = None
self.token_expires_at = None

def authenticate(self):
"""Authenticate using service key to get session token"""
headers = {
'Authorization': f'Basic {self.service_key}',
'Accept': 'application/vnd.nexla.api.v1+json'
}

response = requests.post(f'{self.base_url}/token', headers=headers)
token_data = response.json()

self.access_token = token_data['access_token']
# Calculate expiration time
expires_in = token_data['expires_in']
self.token_expires_at = datetime.now() + timedelta(seconds=expires_in)

def refresh_if_needed(self):
"""Refresh token if it's close to expiring (within 5 minutes)"""
if not self.token_expires_at:
self.authenticate()
return

# Refresh if token expires within 5 minutes
if datetime.now() + timedelta(minutes=5) >= self.token_expires_at:
self.refresh_token()

def refresh_token(self):
"""Refresh the current access token"""
headers = {
'Authorization': f'Bearer {self.access_token}',
'Accept': 'application/vnd.nexla.api.v1+json'
}

response = requests.post(f'{self.base_url}/token/refresh', headers=headers)
token_data = response.json()

self.access_token = token_data['access_token']
expires_in = token_data['expires_in']
self.token_expires_at = datetime.now() + timedelta(seconds=expires_in)

def make_request(self, endpoint, method='GET', **kwargs):
"""Make an authenticated API request with automatic token refresh"""
self.refresh_if_needed()

headers = {
'Authorization': f'Bearer {self.access_token}',
'Accept': 'application/vnd.nexla.api.v1+json'
}

if 'headers' in kwargs:
headers.update(kwargs['headers'])
kwargs['headers'] = headers

response = requests.request(method, f'{self.base_url}{endpoint}', **kwargs)

# Handle token expiration
if response.status_code == 401:
# Token might have expired, try to refresh and retry once
self.refresh_token()
headers['Authorization'] = f'Bearer {self.access_token}'
response = requests.request(method, f'{self.base_url}{endpoint}', **kwargs)

return response

# Usage example
client = NexlaClient('https://api.nexla.io', 'your-service-key')
client.authenticate()

# Make API calls (tokens are automatically refreshed)
response = client.make_request('/teams')
teams = response.json()

JavaScript implementation example:

JavaScript Automatic Token Refresh
class NexlaClient {
constructor(baseUrl, serviceKey) {
this.baseUrl = baseUrl;
this.serviceKey = serviceKey;
this.accessToken = null;
this.tokenExpiresAt = null;
}

async authenticate() {
const encodedKey = btoa(this.serviceKey);
const response = await fetch(`${this.baseUrl}/token`, {
method: 'POST',
headers: {
'Authorization': `Basic ${encodedKey}`,
'Accept': 'application/vnd.nexla.api.v1+json'
}
});

const tokenData = await response.json();
this.accessToken = tokenData.access_token;

// Calculate expiration time
const expiresIn = tokenData.expires_in;
this.tokenExpiresAt = new Date(Date.now() + expiresIn * 1000);
}

async refreshIfNeeded() {
if (!this.tokenExpiresAt) {
await this.authenticate();
return;
}

// Refresh if token expires within 5 minutes
const fiveMinutesFromNow = new Date(Date.now() + 5 * 60 * 1000);
if (fiveMinutesFromNow >= this.tokenExpiresAt) {
await this.refreshToken();
}
}

async refreshToken() {
const response = await fetch(`${this.baseUrl}/token/refresh`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Accept': 'application/vnd.nexla.api.v1+json'
}
});

const tokenData = await response.json();
this.accessToken = tokenData.access_token;

const expiresIn = tokenData.expires_in;
this.tokenExpiresAt = new Date(Date.now() + expiresIn * 1000);
}

async makeRequest(endpoint, options = {}) {
await this.refreshIfNeeded();

const headers = {
'Authorization': `Bearer ${this.accessToken}`,
'Accept': 'application/vnd.nexla.api.v1+json',
...options.headers
};

let response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers
});

// Handle token expiration
if (response.status === 401) {
// Token might have expired, try to refresh and retry once
await this.refreshToken();
headers.Authorization = `Bearer ${this.accessToken}`;
response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers
});
}

return response;
}
}

// Usage example
const client = new NexlaClient('https://api.nexla.io', 'your-service-key');
await client.authenticate();

// Make API calls (tokens are automatically refreshed)
const response = await client.makeRequest('/teams');
const teams = await response.json();

Token Invalidation

Properly invalidating tokens when they're no longer needed is an important security practice. This section explains how to manually invalidate tokens and when this approach is appropriate.

Manual Invalidation

You can invalidate an access token before it expires by making a POST request to the /token/logout endpoint:

Token Invalidation
curl -X POST <nexla-api-endpoint>/token/logout        \
-H "Authorization: Bearer <session-access-token>" \
-H "Accept: application/vnd.nexla.api.v1+json" \
-H "Content-Length: 0"

Invalidation Response

The endpoint responds with HTTP status 200 if the token is successfully invalidated, or 403 if the token is already expired or invalid. After a 200 response, the access token cannot be used for subsequent API calls.

When to Invalidate

Consider invalidating tokens in these scenarios:

  • User Logout: When users explicitly sign out
  • Security Incidents: Suspected token compromise
  • Application Shutdown: Clean shutdown procedures
  • Token Rotation: After obtaining new tokens

Best Practices

Following these best practices ensures that your token management implementation is secure, reliable, and production-ready. These guidelines help prevent common issues and maintain optimal performance.

Token Storage

Proper token storage is crucial for maintaining security and preventing unauthorized access. These practices ensure your tokens remain protected throughout their lifecycle.

  • Secure Storage: Store tokens in secure credential stores or environment variables
  • No Hardcoding: Never hardcode tokens in source code
  • Access Control: Limit access to stored tokens
  • Encryption: Encrypt tokens at rest when possible

Refresh Strategy

A well-planned refresh strategy ensures your application maintains continuous access to the API without interruption. These guidelines help you implement reliable token refresh mechanisms.

  • Proactive Refresh: Refresh tokens before they expire
  • Buffer Time: Refresh tokens 5-10 minutes before expiration
  • Error Handling: Implement retry logic for refresh failures
  • Fallback: Have a fallback authentication method

Monitoring and Logging

Comprehensive monitoring and logging provide visibility into your token management system and help identify issues before they become problems. These practices support both operational excellence and security.

  • Token Usage: Monitor token creation and refresh patterns
  • Error Tracking: Log authentication failures and token issues
  • Performance Metrics: Track token refresh performance
  • Security Events: Monitor for unusual authentication patterns

Production Considerations

Production environments require additional considerations to ensure reliability, scalability, and resilience. These practices help your token management system handle real-world challenges effectively.

  • Load Balancing: Distribute token refresh across multiple instances
  • Circuit Breakers: Implement circuit breakers for authentication failures
  • Health Checks: Monitor authentication service health
  • Disaster Recovery: Plan for authentication service outages

Troubleshooting

When token management issues arise, systematic troubleshooting helps identify and resolve problems quickly. This section covers common issues and provides solutions to get your application back on track.

Common Issues

Most token management problems fall into these categories. Understanding the root causes and solutions helps you resolve issues quickly and prevent them from recurring.

Token Refresh Fails

When token refresh operations fail, it can disrupt your application's ability to maintain continuous API access. This issue typically occurs due to network problems, invalid tokens, or authentication service issues.

Troubleshooting steps:

  1. Verify the current token is still valid
  2. Check network connectivity to authentication endpoints
  3. Ensure proper error handling and retry logic

Token Expiration Errors

Token expiration errors occur when your application fails to handle token expiration gracefully, leading to authentication failures and service interruptions. These errors are common when automatic refresh mechanisms are not properly implemented.

Resolution steps:

  1. Implement proper expiration detection
  2. Add automatic refresh mechanisms
  3. Handle 401 errors properly

Performance Issues

Performance issues in token management can impact application responsiveness and user experience. These problems often stem from inefficient refresh timing, lack of caching, or poor monitoring of authentication endpoints.

Optimization steps:

  1. Optimize token refresh timing
  2. Implement token caching where appropriate
  3. Monitor authentication endpoint performance

Debugging Tips

Effective debugging requires a systematic approach to identify and resolve token management issues. These tips help you troubleshoot problems efficiently and get your system back on track.

  1. Check Token Expiration: Verify token expiration times
  2. Monitor Network Calls: Track authentication request/response cycles
  3. Review Error Logs: Analyze authentication failure patterns
  4. Test Refresh Logic: Verify automatic refresh mechanisms

Next Steps

For comprehensive authentication information, return to the Authentication Overview.