Skip to main content

Authentication

TrackGeek uses Better Auth for modern, secure authentication with support for email/password, social providers, and magic links.

Authentication Methods

TrackGeek supports multiple authentication methods:
  • Email & Password - Traditional authentication
  • Social Providers - Google, GitHub, Discord
  • Magic Links - Passwordless email authentication
  • Bearer Tokens - For API clients and mobile apps

Configuration

Authentication is configured in src/modules/auth/config/auth.config.ts and uses the following environment variables:
.env
# Required
BETTER_AUTH_URL='http://localhost:40287'
BETTER_AUTH_SECRET='your-secret-key-here'
WEB_URL='http://localhost:5173'

# Social Providers (Optional)
GOOGLE_CLIENT_ID='your-google-client-id'
GOOGLE_CLIENT_SECRET='your-google-client-secret'
GITHUB_CLIENT_ID='your-github-client-id'
GITHUB_CLIENT_SECRET='your-github-client-secret'
DISCORD_CLIENT_ID='your-discord-client-id'
DISCORD_CLIENT_SECRET='your-discord-client-secret'

# Email (for magic links)
RESEND_API_KEY='your-resend-api-key'
RESEND_FROM='[email protected]'
Always generate a strong random secret for BETTER_AUTH_SECRET:
openssl rand -base64 32

Email & Password Authentication

Sign Up

Create a new account with email and password:
curl -X POST http://localhost:40287/auth/sign-up/email \
  -H "Content-Type: application/json" \
  -c cookies.txt \
  -d '{
    "email": "[email protected]",
    "password": "securePassword123",
    "name": "John Doe"
  }'
When a user signs up, TrackGeek automatically:
  • Generates a unique username from their email
  • Creates a user profile with default settings
  • Sets session cookies for immediate authentication

Sign In

Authenticate with existing credentials:
curl -X POST http://localhost:40287/auth/sign-in/email \
  -H "Content-Type: application/json" \
  -c cookies.txt \
  -d '{
    "email": "[email protected]",
    "password": "securePassword123"
  }'

Sign Out

End the current session:
curl -X POST http://localhost:40287/auth/sign-out \
  -b cookies.txt

Social Authentication

TrackGeek supports OAuth 2.0 authentication with Google, GitHub, and Discord.

Supported Providers

Google

OAuth 2.0 authentication with Google accounts

GitHub

OAuth 2.0 authentication with GitHub accounts

Discord

OAuth 2.0 authentication with Discord accounts

Setting Up Social Providers

1

Configure Google OAuth

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Enable Google+ API
  4. Create OAuth 2.0 credentials
  5. Add authorized redirect URI: http://localhost:40287/auth/callback/google
  6. Copy Client ID and Client Secret to .env:
GOOGLE_CLIENT_ID='your-google-client-id'
GOOGLE_CLIENT_SECRET='your-google-client-secret'
2

Configure GitHub OAuth

  1. Go to GitHub Developer Settings
  2. Click “New OAuth App”
  3. Set Authorization callback URL: http://localhost:40287/auth/callback/github
  4. Copy Client ID and generate Client Secret
  5. Add to .env:
GITHUB_CLIENT_ID='your-github-client-id'
GITHUB_CLIENT_SECRET='your-github-client-secret'
3

Configure Discord OAuth

  1. Go to Discord Developer Portal
  2. Create a new application
  3. Go to OAuth2 settings
  4. Add redirect: http://localhost:40287/auth/callback/discord
  5. Copy Client ID and Client Secret to .env:
DISCORD_CLIENT_ID='your-discord-client-id'
DISCORD_CLIENT_SECRET='your-discord-client-secret'

Social Sign In Flow

To initiate social authentication, redirect users to:
http://localhost:40287/auth/sign-in/google
http://localhost:40287/auth/sign-in/github
http://localhost:40287/auth/sign-in/discord
<a href="http://localhost:40287/auth/sign-in/google">
  Sign in with Google
</a>

<a href="http://localhost:40287/auth/sign-in/github">
  Sign in with GitHub
</a>

<a href="http://localhost:40287/auth/sign-in/discord">
  Sign in with Discord
</a>
After successful authentication, users are redirected back to WEB_URL with session cookies set.
Magic links provide passwordless authentication via email.
curl -X POST http://localhost:40287/auth/sign-in/magic-link \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]"
  }'
Magic links are sent using Resend. Configure RESEND_API_KEY and RESEND_FROM in your .env file.

Bearer Token Authentication

For API clients and mobile apps, use bearer tokens instead of cookies.

Get Bearer Token

After signing in, request a bearer token:
curl -X POST http://localhost:40287/auth/get-bearer-token \
  -b cookies.txt

Using Bearer Tokens

Include the token in the Authorization header:
curl http://localhost:40287/profile \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
Store bearer tokens securely. Never expose them in client-side code or version control.

Session Management

TrackGeek uses custom session management powered by Better Auth.

Get Current Session

curl http://localhost:40287/auth/get-session \
  -b cookies.txt

Session Response

{
  "user": {
    "id": "uuid",
    "email": "[email protected]",
    "name": "John Doe",
    "username": "johndoe",
    "emailVerified": true,
    "image": "https://avatar.url",
    "createdAt": "2024-01-01T00:00:00.000Z",
    "updatedAt": "2024-01-01T00:00:00.000Z",
    "profile": {
      "bio": "Anime enthusiast",
      "timezone": "America/New_York",
      "avatarUrl": "https://avatar.url",
      "bannerUrl": null,
      "color": "#3B82F6"
    }
  },
  "session": {
    "id": "session-uuid",
    "userId": "uuid",
    "expiresAt": "2024-02-01T00:00:00.000Z"
  }
}

Protected Routes

Protected endpoints require authentication. The API uses NestJS guards to enforce authentication:
src/modules/profile/profile.controller.ts
@Controller("profile")
@UseGuards(AuthGuard)
export class ProfileController {
  @Patch()
  async updateProfile(@Session() session: UserSession, @Body() body: UpdateProfileDto) {
    await this.profileService.updateProfile({
      ...body,
      userId: session.user.id,
    });
  }
}

Example: Making Authenticated Requests

// Browser - cookies are sent automatically
const response = await fetch('http://localhost:40287/profile', {
  method: 'PATCH',
  credentials: 'include',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ bio: 'Updated bio' })
});

Mobile App Authentication

For mobile apps (iOS/Android), TrackGeek supports custom URL schemes for OAuth callbacks:
src/modules/auth/config/auth.config.ts
trustedOrigins: [
  configService.get<string>("WEB_URL"),
  "com.trackgeek.net.mobile.ios://auth/callback",
  "com.trackgeek.net.mobile.android://auth/callback",
  "trackgeek://callback",
]
Configure these URL schemes in your mobile app to handle OAuth redirects.

Security Best Practices

1

Use HTTPS in Production

Always use HTTPS for production deployments to protect credentials and session tokens.
2

Secure Token Storage

  • Browser: Use httpOnly cookies (handled automatically)
  • Mobile: Use secure storage (Keychain, KeyStore)
  • Never store tokens in localStorage or plain text
3

Implement CORS Properly

Configure WEB_URL to only allow trusted origins:
cors: {
  origin: process.env.WEB_URL,
  credentials: true,
}
4

Rotate Secrets Regularly

Change BETTER_AUTH_SECRET periodically and after any security incidents.

Troubleshooting

Common Issues

  • Verify session cookies are being sent with credentials: 'include'
  • Check that bearer token is correctly formatted in Authorization header
  • Ensure session hasn’t expired
  • Verify WEB_URL matches your frontend origin
  • Ensure credentials: 'include' is set in fetch requests
  • Check that withCredentials: true is set for axios
  • Verify OAuth credentials are correct
  • Check callback URLs match exactly
  • Ensure social provider is enabled in their console
  • Review redirect URIs in provider settings

Next Steps

API Reference

Explore all authenticated endpoints

User Profiles

Learn about profile customization

Media Tracking

Start tracking anime, games, and more

Social Features

Discover followers and feed events

Build docs developers (and LLMs) love