Introduction
Authentication is a core part of many apps. GetX provides a clean, reactive way to manage user state, store tokens, and protect routes. With its built‑in dependency injection, reactive state, and middleware, you can build a robust authentication flow with minimal boilerplate. This guide covers everything from login to token persistence and route guards.
- Setting Up the AuthController
Create a controller that holds the user's authentication state. Use reactive variables to reflect login status and user data. The controller will also handle login, logout, and token storage.
- Token Persistence with GetStorage
Use GetStorage to save the authentication token. Initialize GetStorage in main() and then read/write tokens inside the controller. The token can be used in API calls by attaching it to headers.
- Protecting Routes with Middleware
Use GetMiddleware to guard routes that require authentication. Override redirect to check login status and redirect to login if not authenticated.
- Login Page UI
Create a simple login page with reactive validation and loading state. Use GetX or Obx to react to the authentication state.
- Redirecting After Login
After successful login, use Get.offAllNamed to navigate to the home screen and remove the login page from the stack.
- Logout and Cleanup
Implement logout by clearing the token, resetting the reactive state, and navigating to the login screen.
- Using AuthController Throughout the App
Since the controller is permanent (or registered globally), you can access it anywhere with Get.find<AuthController>(). For example, in a profile page to display the user's name.
Best Practices
- Make AuthController permanent – Use
permanent: trueor extendGetxServiceso it never gets disposed. - Use middleware for route protection – Centralise authentication checks.
- Store tokens securely – For production, consider using FlutterSecureStorage for sensitive data.
- Clear token on logout – Always remove the token and reset state.
- Handle token expiration – In your API client, check for 401 responses and automatically redirect to login.
Common Mistakes
- ❌ Not initializing GetStorage before use – Causes errors.
✅ Call
await GetStorage.init()in main. - ❌ Making AuthController non‑permanent – It may be disposed when a route is popped.
✅ Set
permanent: trueor useGetxService. - ❌ Forgetting to redirect after login – User may stay on login page.
✅ Use
Get.offAllNamedto replace the route. - ❌ Not handling token refresh – After logout, the token is gone, but the user may still have access to protected routes if not guarded properly. ✅ Use middleware to check state on every navigation.
Conclusion
GetX makes authentication flows straightforward. By combining reactive state, persistent storage with GetStorage, and route guards with middleware, you can build a secure and user‑friendly login system. The patterns shown here scale from simple apps to complex enterprise solutions.