flutter_next_auth_core 1.1.1
flutter_next_auth_core: ^1.1.1 copied to clipboard
This is a Flutter client library for quickly integrating with NextAuth v4.x backend authorization APIs.
flutter_next_auth_core #
This is a Flutter client library for quickly integrating with NextAuth v4.x backend authorization APIs.
It wraps common NextAuth client capabilities (csrf / session / signin / signout / custom oauth) into a Flutter-friendly NextAuthClient, and provides local token/cookie recovery so you can plug an existing NextAuth backend into mobile apps with minimal glue code.
- Sign in (
email/credentials/ custom OAuth provider) - Fetch / refresh session
- Local token/cookie recovery (via
flutter_secure_storage) - Event notifications (
eventBus: SignedIn/SignedOut/StatusChanged/SessionChanged)
Note: this package only defines an abstract
HttpClient. You must implement it in your app (usingdio,http, etc).
Demo video
https://github.com/user-attachments/assets/e061abd7-552d-48df-818f-6082a53c06ef
https://github.com/user-attachments/assets/ce6d6c48-efb6-4649-867e-37765a6e20fe
π¦ Installation #
Add via CLI #
flutter pub add flutter_next_auth_core
flutter pub get
π₯ Import #
import 'package:flutter_next_auth_core/next_auth.dart';
π§ͺ Example (minimal) #
See /example (a runnable Flutter app):
- How to run:
example/README.md - Entry:
example/lib/main.dart - Dio HttpClient:
example/lib/simple_dio_httpclient.dart - Google OAuth provider example:
example/lib/providers/google_oauth_provider.dart - OAuth backend verification / code-exchange example:
example/lib/oauth_api/route.ts
β οΈ Notes #
- Cookie names must match your backend:
NextAuthConfig.serverSessionCookieName/serverCSRFTokenCookieNamemust match the cookie names configured on your NextAuth server. - Recover session on app start: call
client.recoverLoginStatusFromCache()to restore tokens from secure storage and attempt to fetch session (recommended: use the integrated state management libraries below). - OAuth provider ids: for OAuth sign-in, implement your own
OAuthProviderand register it onNextAuthClient(see the full example underexample/).
π§ Recommended state management libraries #
Strongly recommended for real projects. They wire NextAuthClient session/status changes into your app state so you donβt have to hand-roll listeners and synchronization.
- Call
recoverLoginStatusFromCache()on app startup to attempt session recovery - Listen to
eventBus(SignedIn/SignedOut/StatusChanged/SessionChanged) - Expose auth state to UI (Provider / BLoC state) and centralize side-effects (recover, refetch session, sign out, etc)
Riverpod integration: https://github.com/jcyuan/flutter_next_auth_riverpod
BLoC integration: https://github.com/jcyuan/flutter_next_auth_bloc
π NextAuthClient API Reference #
The following APIs are consistent with the NextAuth.js client API behavior.
Properties #
- config:
NextAuthConfig<T>- Get the configuration objectfinal config = nextAuthClient.config; - status:
SessionStatus- Get current session status- Possible values:
initial,loading,authenticated,unauthenticated
final status = nextAuthClient.status; - Possible values:
- session:
T?- Get current session data (null if not authenticated)final session = nextAuthClient.session; - eventBus:
EventBus- Event bus for listening to authentication events- Available events:
SignedInEvent: Fired when user signs in successfully- Contains
accessToken(Token object with jwt token string and expiration) - IMPORTANT: Save the jwt token from
event.accessToken.tokenfor backend API authorization
- Contains
SignedOutEvent: Fired when user signs outStatusChangedEvent: Fired when session status changesSessionChangedEvent<T>: Fired when session data changes
- Available events:
Event Handling #
Listen to authentication events:
final eventBus = nextAuthClient.eventBus;
// Listen to SignIn event - save jwt token for backend API authorization
eventBus.on<SignedInEvent>().listen((event) {
// event.accessToken is a Token object containing:
// - token: String (jwt token string)
// - expiration: int? (expiration timestamp in milliseconds)
// - isValid: bool (checks if token is valid and not expired)
final jwtToken = event.accessToken.token;
// IMPORTANT: Save this jwtToken to secure storage for later use with your backend API
});
// Listen to SignOut event
eventBus.on<SignedOutEvent>().listen((event) {
// IMPORTANT: Clear the saved jwtToken here
});
Methods #
- recoverLoginStatusFromCache():
Future<void>- Initialize session from cache- Mainly for state management libraries like
next_auth_riverpod/next_auth_bloc(suggested) - To recover login status from cache when app booting up
- Can also be called manually if needed
await nextAuthClient.recoverLoginStatusFromCache(); - Mainly for state management libraries like
- refetchSession():
Future<void>- Refetch session from server- Useful for refreshing local session data
await nextAuthClient.refetchSession(); - signIn(String provider, {...}):
Future<SignInResponse>- Sign in with email, credentials or OAuthprovider:'email','credentials', or OAuth provider id (e.g.,'google','apple')- Must be called in a user interaction context (e.g. button press, tap, etc.)
- Returns
SignInResponsewithokstatus and error information if failed
await nextAuthClient.signIn('credentials', credentialsOptions: CredentialsSignInOptions(...)); await nextAuthClient.signIn('email', emailOptions: EmailSignInOptions(...)); await nextAuthClient.signIn('google', oauthOptions: OAuthSignInOptions(...)); - signOut():
Future<void>- Sign out current user- Clears session and fires
SignedOutEvent
await nextAuthClient.signOut(); - Clears session and fires
- updateSession(T data):
Future<T?>- Update session data on server- Returns updated session data or null if update failed
await nextAuthClient.updateSession({'user': {'name': 'John Doe'}}); - getCSRFToken({bool forceNew = false}):
Future<String?>- Get CSRF tokenforceNew: If true, force fetch a new token from server instead of using cached token- Returns CSRF token string or null if failed
final csrfToken = await nextAuthClient.getCSRFToken(); final newCsrfToken = await nextAuthClient.getCSRFToken(forceNew: true); - setLogger(Logger logger):
void- Set custom logger instancenextAuthClient.setLogger(MyCustomLogger()); - registerOAuthProvider(String providerId, OAuthProvider provider):
void- Register OAuth providerproviderId: Unique identifier for the provider (e.g.,'google','apple')provider: OAuthProvider implementation- IMPORTANT: You need to implement your own OAuth client provider
- The provider is mainly used to provide
idTokenorauthorizationCodereturned from the OAuth client package (likegoogle_sign_in,apple_sign_in, etc) for server-side verification and to return your server's session information - For backend verification logic, please see the example code in
/lib/oauth_api/rout.ts
import 'package:next_auth_client_example/providers/google_oauth_provider.dart'; nextAuthClient.registerOAuthProvider('google', GoogleOAuthProvider()); - removeOAuthProvider(String providerId):
void- Remove registered OAuth providernextAuthClient.removeOAuthProvider('google');
β οΈ Important Notes #
Cookie Name Matching #
The cookie names configured in NextAuthConfig must exactly match your server-side NextAuth.js configuration. Mismatched cookie names will cause authentication failures.
Example server-side NextAuth.js configuration:
export default NextAuth({
cookies: {
sessionToken: {
name: 'next-auth.session-token', // or your custom name
options: {
// cookie options
}
},
csrfToken: {
name: 'next-auth.csrf-token', // or your custom name
options: {
// cookie options
}
}
}
})
See also #
Riverpod integration: https://github.com/jcyuan/flutter_next_auth_riverpod
BLoC integration: https://github.com/jcyuan/flutter_next_auth_bloc