User Onboarding API - Technical Documentation
Overview
The User Onboarding API provides functionality to track and complete user onboarding processes within the Nimbly platform. This API allows marking users as having completed their onboarding flow, which is essential for user experience tracking and analytics.
Architecture
Domain-Driven Design
The onboarding feature follows the established DDD pattern in the api-users microservice:
src/
├── controllers/user.controller.ts # HTTP handler for onboarding endpoint
├── domains/user/
│ ├── user.usecase.ts # Business logic for onboarding
│ ├── user.schema.ts # MongoDB schema with isOnboarded field
│ ├── user.validator.ts # Input validation
│ └── repository/ # Data persistence layer
├── routes/user.router.ts # Route definition
└── models/user.firebase.ts # Firebase user model
API Endpoint
Complete User Onboarding
Endpoint: POST /complete-onboarding
Authentication: Required (JWT Bearer Token)
Description: Marks the authenticated user as having completed the onboarding process.
Request:
POST /complete-onboarding
Authorization: Bearer <jwt_token>
Content-Type: application/json
{}Response:
{
"data": "Onboarding completed successfully",
"error": null
}Error Responses:
-
404 Not Found
{ "data": "User not found", "error": "not-found" } -
400 Bad Request
{ "data": "Failed to complete onboarding", "error": "invalid" }
Implementation Details
Data Flow
-
Route Handler (
src/routes/user.router.ts:363-366)- Receives POST request at
/complete-onboarding - Applies authentication middleware
- Validates request using Joi schema
- Passes to controller
- Receives POST request at
-
Controller (
src/controllers/user.controller.ts:619-628)- Extracts user context from authenticated request
- Calls use case with user context
- Returns standardized response
-
Use Case (
src/domains/user/user.usecase.ts:925-970)- Retrieves current user from MongoDB
- Updates
isOnboardedfield totruein both Firebase and MongoDB - Publishes update event for side effects
- Handles errors and returns appropriate response
-
Data Persistence
Database Schema
MongoDB Schema (src/domains/user/user.schema.ts:72-75)
isOnboarded: {
type: Boolean,
default: false
}Firebase Model (src/models/user.firebase.ts:24,43)
public isOnboarded?: boolean;
// Constructor defaults to false if not provided
this.isOnboarded = data.isOnboarded || false;Validation
The endpoint uses minimal validation (src/domains/user/user.validator.ts:98-100):
completeOnboarding: Joi.object({
body: Joi.object({}).unknown(true),
}).unknown(true)No request body parameters are required as the API operates on the authenticated user’s context.
Key Features
1. Automatic User Context
The API automatically identifies the user from the JWT token, eliminating the need to pass user identifiers in the request body.
2. Dual Storage Sync
Updates are synchronized between MongoDB (primary database) and Firebase (authentication service) to maintain data consistency.
3. Event-Driven Architecture
The completion of onboarding triggers a PubSub event (user:updateSideEffect) that can be consumed by other services for:
- Analytics tracking
- Email notifications
- Feature unlocking
- Dashboard updates
4. Backward Compatibility
The implementation handles legacy users who don’t have the isOnboarded field by:
- Adding the field if it doesn’t exist
- Setting appropriate defaults
- Ensuring smooth migration
5. Idempotency
The API is idempotent - calling it multiple times for the same user will not cause errors or inconsistent states.
Security Considerations
- Authentication Required: The endpoint requires a valid JWT token
- User Isolation: Users can only update their own onboarding status
- No Sensitive Data: The endpoint doesn’t expose or modify sensitive user information
- Audit Trail: Updates trigger events that can be logged for compliance
Testing
The implementation includes comprehensive unit tests (src/domains/user/user.usecase.test.ts:1253-1384):
- Success scenarios with proper updates
- User not found handling
- Error handling for database failures
- Legacy user migration (adding
isOnboardedfield) - Event publishing verification
Test Coverage Areas
- User exists and successfully completes onboarding
- User not found returns appropriate error
- Database update failures are handled gracefully
- Field is added for users without
isOnboarded - Events are published correctly
Integration Points
Dependencies
- Authentication Middleware: Validates JWT tokens
- MongoDB: Primary data storage
- Firebase Admin SDK: User authentication sync
- PubSub: Event distribution
Downstream Services
Services that may consume the user:updateSideEffect event:
- Analytics service for tracking onboarding completion rates
- Notification service for welcome emails
- Feature flag service for enabling post-onboarding features
Performance Considerations
- Timeout: Operations have a 30-second timeout for database updates
- Async Operations: Firebase and MongoDB updates happen sequentially to ensure consistency
- Event Publishing: Asynchronous to avoid blocking the response
Error Handling
The implementation follows a defensive programming approach:
- Try-Catch Blocks: All database operations are wrapped in error handling
- Logging: Errors are logged with context for debugging
- Graceful Degradation: Failures return meaningful error messages
- Rollback: No partial updates - either all succeed or all fail
Future Enhancements
Potential improvements for the onboarding API:
- Onboarding Steps Tracking: Track individual onboarding steps completion
- Onboarding Analytics: Capture time spent, drop-off points
- Customizable Flows: Support different onboarding flows per organization
- Bulk Operations: Admin endpoint to mark multiple users as onboarded
- Onboarding Reset: Allow admins to reset onboarding status
- Webhooks: Notify external systems when onboarding completes
API Usage Example
// Client-side implementation
async function completeUserOnboarding(token) {
try {
const response = await fetch('https://api.nimbly.com/complete-onboarding', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const result = await response.json();
if (result.error) {
console.error('Onboarding failed:', result.error);
return false;
}
console.log('Onboarding completed:', result.data);
return true;
} catch (error) {
console.error('Network error:', error);
return false;
}
}Monitoring & Observability
Metrics to Track
- Onboarding completion rate
- API response times
- Error rates by type
- Daily/weekly/monthly completion trends
Logging
All operations log:
- User ID attempting onboarding
- Success/failure status
- Error details if failed
- Timestamp of completion
Alerts
Consider setting up alerts for:
- High error rates (>5% failures)
- Slow response times (>2 seconds)
- Database connection issues
- Firebase sync failures
Conclusion
The User Onboarding API provides a simple yet robust mechanism for tracking user onboarding completion. Its integration with both MongoDB and Firebase ensures data consistency, while the event-driven architecture enables seamless integration with other platform services. The implementation follows best practices for security, error handling, and maintainability, making it a reliable component of the user management system.