My Current Setup
I’m working with:
- Next.js purely for frontend (no backend routes)
- Custom Java backend API
- External OAuth provider for authentication
- NextAuth for session management
Main Question: How do I properly handle OAuth flow when Next.js is frontend-only?
Important notes:
- Next.js should NOT handle backend logic
- I already have username/password auth working with CredentialsProvider
- This is specifically about external OAuth provider integration
Approach Option 1:
-
Frontend redirects user to OAuth provider URL
- Question: What’s the proper URL construction method?
-
OAuth provider redirects back with authorization code
-
Frontend sends code to Java backend
- Should I use
useEffectto automatically send the code when redirect page loads?
- Should I use
-
Java backend returns JWT tokens
-
Store JWT and user data in NextAuth session
- How exactly do I integrate this into NextAuth? Which file handles this logic?
Approach Option 2:
- Frontend redirects to Java backend endpoint
- Backend handles OAuth flow completely
- Backend redirects back to frontend with some data
- What data should be passed here?
- Frontend retrieves JWT from backend somehow
- Problem: How does frontend get tokens after all these redirects?
- Setup NextAuth session
Why I need help: Online tutorials assume Next.js handles both frontend and backend, but I need the Java backend to manage all security operations.
// Current NextAuth config
const authOptions = {
providers: [
// Need custom OAuth provider here
],
callbacks: {
// How to handle custom backend JWT?
}
}
Versions: Next.js 15.1.6, NextAuth 4.24.11, React 19.0.0