In dieser Anleitung erfährst du, wie du TikTok OAuth erfolgreich in deine Next.js-Anwendung integrierst. Basierend auf realen Erfahrungen mit der TikTok Developer API und NextAuth.js v5.
Der kritische Parameter-Unterschied
Das wichtigste Learning: TikTok OAuth verwendet client_key
statt dem Standard client_id
Parameter!
Das Problem
NextAuth.js generiert standardmäßig OAuth URLs mit client_id
:
https://www.tiktok.com/v2/auth/authorize?client_id=your-app-id&...
TikTok erwartet aber client_key
:
https://www.tiktok.com/v2/auth/authorize?client_key=your-app-id&...
Die Lösung: Custom Provider Implementation
// packages/auth/src/providers.ts
export function TikTok(options: OAuthUserConfig<TikTokProfile>): OAuthConfig<TikTokProfile> {
const config = getTikTokConfig();
return {
id: 'tiktok',
name: 'TikTok',
type: 'oauth',
// KRITISCH: Direkte client_key Parameter-Spezifikation
authorization: {
url: config.endpoints.authorize,
params: {
scope: getTikTokScopes(),
response_type: 'code',
client_key: options.clientId, // ← Das ist der Schlüssel!
},
},
// Fallback: URL-Interception für Parameter-Transformation
async authorize(params, request) {
let authUrl = new URL(config.endpoints.authorize);
// Stelle sicher, dass client_key verwendet wird
authUrl.searchParams.set('client_key', options.clientId);
authUrl.searchParams.delete('client_id'); // Entferne falschen Parameter
// Weitere Parameter...
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', getTikTokScopes());
authUrl.searchParams.set('redirect_uri', params.redirect_uri);
authUrl.searchParams.set('state', params.state);
return { url: authUrl.toString() };
},
token: config.endpoints.token,
userinfo: config.endpoints.userinfo,
profile(profile) {
return {
id: profile.data.user.open_id,
name: profile.data.user.display_name,
image: profile.data.user.avatar_url,
email: null, // TikTok stellt keine E-Mail bereit
};
},
};
}
Sandbox vs. Production Environment
Environment-Konfiguration
// packages/auth/src/utils.ts
export type TikTokEnvironment = 'sandbox' | 'production';
export function getTikTokEnvironment(): TikTokEnvironment {
return (process.env.TIKTOK_ENVIRONMENT as TikTokEnvironment) || 'sandbox';
}
export function getTikTokConfig() {
const environment = getTikTokEnvironment();
return {
endpoints: {
authorize: 'https://www.tiktok.com/v2/auth/authorize',
token: 'https://open.tiktokapis.com/v2/oauth/token/',
userinfo: 'https://open.tiktokapis.com/v2/user/info/',
},
scopes: {
sandbox: [
'user.info.basic',
'user.info.profile',
'user.info.stats'
],
production: [
'user.info.basic',
'user.info.profile',
'user.info.stats',
'video.upload',
'video.publish'
]
}
};
}
Sandbox Environment Besonderheiten
Wichtige Unterschiede zwischen Sandbox und Production:
- Scopes: Sandbox hat eingeschränkte Berechtigungen
- Rate Limits: Niedrigere Limits in Sandbox
- Domain Verification: Nicht erforderlich für Sandbox
- Daten: Sandbox nutzt Test-Daten, nicht echte User-Profile
NextAuth.js v5 Konfiguration
Basis-Setup
// packages/auth/src/nextauth.ts
import NextAuth, { type NextAuthConfig } from 'next-auth';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from '@tiktok-saas/database';
import { TikTok } from './providers';
const authConfig: NextAuthConfig = {
secret: process.env.NEXTAUTH_SECRET,
adapter: PrismaAdapter(prisma),
providers: [
TikTok({
clientId: process.env.TIKTOK_CLIENT_KEY!,
clientSecret: process.env.TIKTOK_CLIENT_SECRET!,
}),
],
pages: {
signIn: '/auth/signin',
error: '/auth/error',
},
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 Tage
},
debug: process.env.NODE_ENV === 'development',
};
export const { handlers, signIn, signOut, auth } = NextAuth(authConfig);
Erweiterte Session-Types
// Type Augmentation für TikTok Profile Daten
declare module 'next-auth' {
interface Session {
user: {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
tikTokProfile?: {
unionId?: string;
bio?: string;
isVerified?: boolean;
followerCount?: number;
followingCount?: number;
likesCount?: number;
videoCount?: number;
profileDeepLink?: string;
};
};
}
}
Environment Variables Setup
Erforderliche Variablen
# .env.local
NEXTAUTH_SECRET="generated-secret-key"
NEXTAUTH_URL="http://localhost:3000"
# TikTok OAuth Credentials
TIKTOK_CLIENT_KEY="your-app-client-key"
TIKTOK_CLIENT_SECRET="your-app-client-secret"
TIKTOK_ENVIRONMENT="sandbox"
# Database
DATABASE_URL="postgresql://user:password@localhost:5432/database"
Vercel Production Deployment
# Vercel Environment Variables hinzufügen
vercel env add NEXTAUTH_SECRET production
vercel env add NEXTAUTH_URL production
vercel env add TIKTOK_CLIENT_KEY production
vercel env add TIKTOK_CLIENT_SECRET production
vercel env add TIKTOK_ENVIRONMENT production
vercel env add DATABASE_URL production
Häufige Fehler und Lösungen
1. "Server Configuration Error"
Ursache: Fehlende NEXTAUTH_SECRET
Environment Variable
Lösung:
# Generiere ein neues Secret
openssl rand -base64 32
# Füge es zu deinen Environment Variables hinzu
NEXTAUTH_SECRET="generated-secret-here"
2. "Invalid client_id" von TikTok
Ursache: NextAuth.js sendet client_id
statt client_key
Lösung: Verwende den Custom Provider von oben mit direkter client_key
Spezifikation.
3. "Access Denied" während OAuth
Ursache: Falsche Redirect URI oder App-Konfiguration
Lösung:
- Prüfe TikTok Developer Console Redirect URIs
- Stelle sicher, dass Production URLs exakt übereinstimmen
- Verwende HTTPS für Production Domains
4. TypeScript Compilation Errors
Ursache: Fehlende Type Annotations für OAuth Context
Lösung:
async authorize(params: any, request: { url: string; provider: { clientId: string } }) {
// Proper typing verhindert Compilation-Fehler
}
Testing und Validation
Manuelle Validierung
- Browser Developer Tools öffnen → Network Tab
- "Continue with TikTok" klicken
- Authorization URL prüfen:
- ✅ Enthält
client_key=your-app-id
- ❌ Enthält NICHT
client_id
- ✅ Enthält
- TikTok Authorization Page lädt ohne Fehler
Automatisierte Tests
// e2e/tiktok-oauth-validation.spec.ts
import { test, expect } from '@playwright/test';
test('TikTok OAuth flow uses correct parameters', async ({ page }) => {
await page.goto('/auth/signin');
// Überwache Network Requests
const authRequestPromise = page.waitForRequest(/tiktok\.com.*authorize/);
await page.click('button:has-text("Continue with TikTok")');
const authRequest = await authRequestPromise;
const url = new URL(authRequest.url());
// Validiere Parameter
expect(url.searchParams.get('client_key')).toBeTruthy();
expect(url.searchParams.get('client_id')).toBeNull();
expect(url.searchParams.get('response_type')).toBe('code');
});
Deployment Checklist
Vor dem Deployment
- Environment Variables in Vercel konfiguriert
- TikTok App Redirect URIs aktualisiert
- Domain Verification (für Production)
- TypeScript Compilation erfolgreich
- Tests bestehen
Nach dem Deployment
- OAuth Flow manuell testen
- Network Requests auf
client_key
Parameter prüfen - TikTok Authorization Page lädt erfolgreich
- Error Handling funktioniert korrekt
Best Practices
Security
- Niemals Secrets committen - Verwende Environment Variables
- HTTPS in Production - TikTok erfordert sichere Callbacks
- Token Refresh - Implementiere Token-Erneuerung für Langzeit-Zugriff
Development Workflow
- Sandbox zuerst - Teste immer in Sandbox Environment
- Environment Separation - Separate Apps für Dev/Staging/Production
- Logging - Umfassendes Error Logging für OAuth Debugging
Troubleshooting
- Parameter Validation - Prüfe Authorization URLs in Browser DevTools
- TikTok Developer Console - Überwache App Usage und Errors
- NextAuth.js Debug Mode - Aktiviere Debug Logging für Development
Dieser Guide basiert auf echten Implementierungserfahrungen und löst die häufigsten TikTok OAuth Probleme. Mit diesen Patterns sollte deine Integration reibungslos funktionieren.