Authentication Flow
The authentication system validates user credentials by making a direct API call to Riot’s account lookup endpoint:Faker)# (e.g., KR1)function validateCredentials(gameName, tagLine, apiKey) {
const errors = [];
const g = typeof gameName === 'string' ? gameName.trim() : '';
const t = typeof tagLine === 'string' ? tagLine.replace(/^#/, '').trim() : '';
const k = typeof apiKey === 'string' ? apiKey.trim() : '';
if (!g || g.length < 2) errors.push('Game Name must be at least 2 characters');
if (!t) errors.push('Tag Line is required');
if (!k) errors.push('API Key is required');
return { gameName: g, tagLine: t, apiKey: k, errors };
}
# prefixes are strippedconst RIOT_ACCOUNT_URL = (gameName, tagLine) =>
`https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`;
const response = await fetch(url, {
headers: { 'X-Riot-Token': apiKey },
cache: 'no-store',
});
if (!response.ok) {
if (response.status === 401) {
throw new Error('Invalid API key or Riot account.');
}
if (response.status === 403) {
throw new Error('API key forbidden or rate limited.');
}
if (response.status === 404) {
throw new Error('Riot ID not found. Check Game Name and Tag Line.');
}
if (response.status === 429) {
throw new Error('Too many requests. Please try again later.');
}
throw new Error(data?.status?.message || `Riot API error (${response.status}).`);
}
Session Management
Agent LoL uses JWT-based sessions for stateless authentication. This approach is ideal for serverless deployments and doesn’t require a database.Session Configuration
auth.js
- Sessions last 30 days before requiring re-authentication
- Session tokens are updated every 24 hours to maintain freshness
- JWT tokens are encrypted using the
AUTH_SECRETenvironment variable
JWT Token Structure
The JWT token stores user data and the API key securely:auth.js
Session Callback
The session callback determines what data is exposed to the client:auth.js
session.user.puuid- Unique player identifiersession.user.gameName- Display namesession.user.tagLine- Tag identifier
Protected Routes
Pages are protected using theauth() helper from NextAuth:
src/app/page.js
- Unauthenticated users are redirected to
/login - The
callbackUrlparameter preserves the intended destination - Session data is available in server components
Client-Side Authentication
The login page uses React’suseActionState for form handling:
src/app/login/page.js
- Progressive enhancement - Works without JavaScript
- Client-side validation before server submission
- Error feedback displayed directly in the form
- No full page refresh for better UX
Security Best Practices
Agent LoL implements several security measures to protect user credentials:
1. API Key Storage
- API keys are never exposed to the browser
- Stored only in encrypted JWT tokens
- Used exclusively in server-side API routes
2. Session Encryption
Generate a strongAUTH_SECRET for production:
- Encrypts all JWT session tokens
- Should be at least 32 characters
- Must be kept secure and never committed to version control
3. Rate Limiting
Riot API keys have built-in rate limits:- Development keys: 20 requests/second, 100 requests/2 minutes
- Production keys: Higher limits based on approval
4. HTTPS Only
NextAuth automatically sets secure cookie flags when:NODE_ENV === 'production'- The site is accessed via HTTPS
5. No Database Required
By using JWT sessions:- No sensitive data is stored in a database
- Reduces attack surface
- Simplifies deployment and scaling
Environment Variables
Required environment variables for authentication:.env.local
Testing Authentication
To test the authentication flow:-
Start the development server:
-
Navigate to the login page:
-
Test with invalid credentials to verify error handling:
- Wrong API key → “Invalid API key or Riot account”
- Non-existent Riot ID → “Riot ID not found”
- Empty fields → Client-side validation errors
- Test with valid credentials to confirm successful authentication
Troubleshooting
”Invalid API key or Riot account”
Cause: The API key is expired, invalid, or doesn’t match the Riot account. Solution: Generate a fresh API key from developer.riotgames.com.Session Cookie Not Set
Cause: Missing or invalidAUTH_SECRET.
Solution:
.env.local.
”Riot API error (401)”
Cause: API key authentication failed. Solution: Verify your API key hasn’t expired. Development keys expire every 24 hours.”Too many requests”
Cause: Rate limit exceeded. Solution: Wait 2 minutes before retrying, or apply for a production API key with higher limits.Next Steps
API Integration
Learn how to use the Riot API with authenticated sessions
Configuration
Configure environment variables for production deployment
