Customization Approaches
There are two main ways to customize authentication handlers:- Run custom code before auth handlers - Intercept auth routes in middleware
- Run code after authentication - Use the
onCallbackhook
- Login parameters via query parameters or static configuration
- Session data modification using the
beforeSessionSavedhook - Logout redirects using query parameters
Running Custom Code Before Auth Handlers
Intercept authentication routes in your middleware to add custom logic before the SDK processes them.- Next.js 15 (middleware.ts)
- Next.js 16 (proxy.ts)
middleware.ts
Use Cases
1. Force specific authentication parameters:Running Code After Callback
Use theonCallback hook to run custom logic after authentication succeeds.
Using the onCallback Hook
lib/auth0.ts
Hook Parameters
Common Use Cases
1. Create user record:Modifying Session Before Save
Use thebeforeSessionSaved hook to modify session data before it’s persisted.
lib/auth0.ts
Common Use Cases
1. Add custom claims:Combining Customizations
You can combine multiple customization approaches:lib/auth0.ts
Best Practices
- Validate all user inputs to prevent security vulnerabilities
- Keep hooks fast - Avoid long-running operations that slow down authentication
- Handle errors gracefully - Always catch and log errors in hooks
- Don’t store sensitive data in sessions unless necessary
- Use TypeScript for type safety when modifying sessions
- Test thoroughly - Test all customizations in development before deploying
Security Considerations
Troubleshooting
Hook not being called
If your hooks aren’t executing:- Ensure hooks are defined in the
Auth0Clientconstructor - Check for errors in the hook function (use try-catch)
- Verify the auth flow is completing successfully
Redirect not working
If custom redirects aren’t working:- Ensure the
returnToURL is registered in Auth0 Allowed Callback URLs - Check that you’re returning the correct format from
onCallback - Verify the URL is properly encoded
Session modifications not persisting
If session changes aren’t saved:- Use
beforeSessionSaved, notonCallback, for session modifications - Ensure you’re returning the modified session object
- Check that the session size doesn’t exceed cookie limits (4KB)