NextAuth API (api/auth/[...nextauth].ts)¶
Endpoint Overview¶
Configures and manages authentication flows, session handling, and user authorization using NextAuth.js. Supports multiple authentication providers and implements secure session management.
Request Handlers¶
GET/POST¶
- Multiple endpoints under
/api/auth/*: /api/auth/signin- Sign in/api/auth/signout- Sign out/api/auth/session- Session info/api/auth/csrf- CSRF tokens/api/auth/providers- Available providers-
/api/auth/callback/*- OAuth callbacks -
Response varies by endpoint, example session response:
- Status: 200 OK, 401 Unauthorized, 403 Forbidden, 404 Not Found
Error Handling¶
export default NextAuth({
providers: [...],
callbacks: {
async jwt({ token, user, account }) {
try {
if (user) {
token.id = user.id;
token.role = user.role;
}
return token;
} catch (error) {
console.error('JWT callback error:', error);
throw error;
}
}
}
});
Common errors: - 401: Invalid credentials - 403: Email not verified - 429: Too many attempts - 404: Provider not found - 500: Authentication error
Usage Example¶
// Sign in with credentials
const result = await signIn('credentials', {
email: 'user@example.com',
password: 'password123',
redirect: false
});
// Sign out
await signOut({
redirect: true,
callbackUrl: '/'
});
// Get session
const session = await getSession();
Implementation Details¶
- Configures authentication providers:
- Credentials (email/password)
- OAuth (Google, GitHub, Microsoft)
- Implements JWT strategy
- 30-day session lifetime
- Custom JWT callbacks
- Session management
- CSRF protection
- Rate limiting
- Secure cookies
- Token encryption
Pages/Components Referenced By¶
- Sign In API - Authentication endpoint
- Register API - User registration
- Current API - Session info
- Email API - Email verification
- Layout Provider - Auth wrapper
Notes¶
- Implements password policies
- Handles OAuth flows
- Manages refresh tokens
- Tracks login attempts
- Supports multiple providers
- Uses JWT strategy
- Includes CSRF protection
- Secure session handling
- Rate limited endpoints