This document describes the Discord OAuth2 integration implementation for the TeachLink authentication flow.
##Overview
The Discord OAuth integration allows users to authenticate using their Discord account, providing a seamless signup/login experience.
This project uses URL-based API versioning to protect clients from breaking changes.
-
Stable API paths continue to be served at
/api/v1/* -
Legacy paths under
/api/*remain supported through a compatibility layer -
Older
/api/*requests are rewritten to/api/v1/*and receive deprecation headers -
OAuth2 Flow: Implements the standard Discord OAuth2 authorization code flow
-
Security: Uses state parameter to prevent CSRF attacks
-
Email Verification: Requires Discord accounts to have verified emails
-
Avatar Support: Fetches and displays user avatars from Discord
-
Edge Runtime: Optimized for Edge deployment for fast performance
-
OAuth Utilities (
src/lib/discord/oauth.ts)getDiscordAuthUrl(): Generates Discord authorization URLexchangeCodeForToken(): Exchanges authorization code for access tokengetDiscordUser(): Fetches user information from DiscordgetDiscordAvatarUrl(): Generates avatar URL with fallbackgenerateState(): Generates random state for CSRF protection
-
API Routes
GET /api/auth/discord: Initiates OAuth flowGET /api/auth/discord/callback: Handles OAuth callback
-
UI Components
DiscordButton: Reusable button component for Discord auth- Updated login/signup pages with Discord button
User clicks Discord button
↓
GET /api/auth/discord
↓
Generate state, set cookie, redirect to Discord
↓
User authorizes on Discord
↓
Discord redirects to callback with code
↓
GET /api/auth/discord/callback
↓
Validate state, exchange code for token
↓
Fetch user info from Discord
↓
Create/update user session
↓
Return auth response
Add the following environment variables to your .env file:
DISCORD_CLIENT_ID=your_discord_client_id
DISCORD_CLIENT_SECRET=your_discord_client_secret
DISCORD_REDIRECT_URI=http://localhost:3000/api/auth/discord/callback- Go to Discord Developer Portal
- Create a new application
- Navigate to "OAuth2" → "General"
- Copy the Client ID and generate a Client Secret
- Add your redirect URI under "Redirects"
- Save the credentials in your environment variables
For production, use your actual domain:
DISCORD_REDIRECT_URI=https://yourdomain.com/api/auth/discord/callback- CSRF Protection: State parameter is stored in httpOnly cookie and validated on callback
- HTTPS Required: In production, always use HTTPS for OAuth callbacks
- Secret Management: Never commit Discord secrets to version control
- Email Verification: Only accepts Discord accounts with verified emails
- Rate Limiting: All OAuth endpoints are rate-limited
Initiates Discord OAuth flow.
Response: Redirect to Discord authorization page
Cookie: Sets discord_oauth_state for CSRF protection
Handles Discord OAuth callback.
Query Parameters:
code: Authorization code from Discordstate: State parameter for CSRF validationerror: OAuth error (if any)
Response:
{
"message": "Discord authentication successful",
"user": {
"id": "user_id",
"name": "username",
"email": "user@example.com",
"avatar": "avatar_url",
"provider": "discord",
"providerId": "discord_user_id"
},
"token": "jwt_token"
}Error Responses:
400: Invalid parameters, unverified email, or OAuth error500: Internal server error
Test OAuth utility functions:
pnpm test src/lib/discord/__tests__/oauth.test.tsTest API routes:
pnpm test src/app/api/auth/discord/__tests__/route.test.ts
pnpm test src/app/api/auth/discord/callback/__tests__/route.test.tsTest complete OAuth flow:
pnpm test:e2e e2e/auth/discord.spec.ts- Implement token refresh logic
- Add Discord role-based access control
- Store Discord tokens for API integrations
- Add Discord guild membership verification
- Implement account linking (multiple OAuth providers)
-
"Discord OAuth configuration is missing"
- Ensure all environment variables are set
- Check that variables are loaded in the Edge runtime
-
"Invalid state parameter"
- Clear cookies and try again
- Ensure state cookie is being set correctly
-
"Discord email must be verified"
- User must verify their email on Discord first
- Cannot use Discord accounts without verified email
-
Callback URL mismatch
- Ensure redirect URI matches exactly what's configured in Discord Developer Portal
- Check for trailing slashes or protocol differences (http vs https)