Skip to main content

Middleware Functions

The middleware functions provide the core business logic interface between your UI components and backend services. These functions handle authentication, data management, real-time communication, and application workflows for job matching platforms.


📋 Table of Contents


🔐 Authentication & Session Management

FunctionDescriptionUsage Example
onActionLoginAuthenticate user with email/password credentialsLogin forms, authentication flows
onActionLogoutProcess user logout and clear session dataLogout buttons, session termination
onActionSignUpRegister new job seeker or employer accountRegistration forms, user onboarding
onSuccessLoginHandle post-login redirect and initializationLogin success handling
onSuccessLogoutHandle post-logout cleanup and redirectLogout success handling
onActionResendVerificationEmailResend email verification to userEmail verification workflows
onRequestPasswordChangeInitiate password reset processForgot password forms
onResetPasswordSubmitComplete password reset with token validationPassword reset completion
onSessionStateUpdateHandle session state changes and updatesSession management, token refresh
isLoggedInCheck if user is currently authenticatedConditional rendering, route guards
isNotLoggedInCheck if user is not authenticatedAuthentication prompts, access control

👤 User Management

FunctionDescriptionUsage Example
onUpdateUserUpdate job seeker or employer profile informationProfile editing forms
onLockUserLock/suspend user account (admin functionality)Admin user management panel
onUnlockUserUnlock/restore user account (admin functionality)Admin user management panel
onDeactivateAccountDeactivate current user accountAccount deletion flows
onCreateInvitationCreate team member invitation for organizationTeam member invitations
onDeleteInvitationRemove/cancel pending user invitationInvitation management
onAcceptInvitationAccept organization team invitationInvitation acceptance workflow
onChangePasswordUpdate user's current passwordPassword change forms
onChangeEmailUpdate user's email addressEmail change forms

🏢 Organization Management

FunctionDescriptionUsage Example
onCreateOrganizationCreate new employer organizationOrganization setup forms
onUpdateOrganizationUpdate organization profile and detailsOrganization profile editing
onFilterOrganizationsFilter and search organization listingsOrganization directory
onGetMoreOrganizationProductsLoad more job postings for organizationOrganization job listings pagination

💼 Job Posting & Catalog Management

FunctionDescriptionUsage Example
onCreateProductCreate new job postingJob posting creation forms
onUpdateProductUpdate existing job postingJob posting editing forms
onFilterProductsFilter and search job listingsJob search and filtering
onGetMoreProductsLoad more job postings (pagination)Job listings pagination
onGetAttributesFetch job skills and attributesSkill selection, job filtering
onGetCategoriesLoad job categoriesCategory-based navigation
onCreateProductAttachmentUpload job-related file attachmentJob description attachments
onDeleteProductAttachmentRemove job posting attachmentAttachment management

📝 Application & Order Management

FunctionDescriptionUsage Example
onCreateOrderCreate new job applicationJob application submission
onActionUpdateOrderUpdate application status and detailsApplication management, status updates
onFilterOrdersFilter and search job applicationsApplication search and filtering
onGetMoreOrdersLoad more applications (pagination)Application history pagination

💬 Real-time Communication

FunctionDescriptionUsage Example
onCreateTopicCreate new chat conversation between employer and candidateApplication-based chat initialization
onSubscribeToTopicSubscribe to chat topic for real-time updatesReal-time messaging setup
onSendMessageSend message in employer-candidate conversationMessage sending interface
onGetMoreMessagesLoad previous message historyChat history pagination
onGetMoreTopicsLoad more conversation topicsChat topics list pagination
onUpdateMessageReadStatusMark messages as readRead status tracking
appendMessagesToStateAdd new messages to application stateReal-time message updates
onSocketSubscribeToUserIdSubscribe to user-specific real-time updatesUser notification system
onSocketUnSubscribeToUserIdUnsubscribe from user real-time updatesCleanup on logout/unmount
onSocketSubscribeToOrganizationIdSubscribe to organization real-time updatesEmployer notification system
onSocketUnSubscribeToOrganizationIdUnsubscribe from organization updatesCleanup on navigation

🔍 Search & Filtering

FunctionDescriptionUsage Example
onChangeSearchFilterUpdate job search criteriaSearch input handling
onSelectFilterAdd filter to job search selectionFilter selection UI
onRemoveSelectedFilterRemove specific filter from selectionIndividual filter removal

🧭 Navigation & UI Control

FunctionDescriptionUsage Example
onActionToggleMenuToggle mobile/sidebar menuMenu button handling
redirectProgrammatic navigationRoute changes, redirects

📄 Pagination

All pagination functions handle loading additional items for their respective data types:

FunctionDescriptionUsage Example
onGetMoreProductsLoad additional job postingsJob listings infinite scroll
onGetMoreOrdersLoad additional applicationsApplication history pagination
onGetMoreOrganizationProductsLoad more organization job postingsOrganization job catalog pagination
onGetMoreMessagesLoad additional chat messagesChat history loading
onGetMoreTopicsLoad additional conversation topicsChat topics list pagination

🚀 Usage Patterns

Basic Authentication Usage

function LoginForm({ middleware }) {
const handleLogin = async (email, password) => {
const result = await middleware.onActionLogin({ email, password });

if (result.ok) {
// Login successful - redirect to dashboard
console.log('User logged in:', result.value);
} else {
// Handle authentication error
console.error('Login failed:', result.error);
}
};

return (
<form onSubmit={handleLogin}>
{/* Email and password fields */}
</form>
);
}

Job Posting Creation Pattern

const handleCreateJobPosting = async (organizationId, jobData) => {
try {
const result = await middleware.onCreateProduct(organizationId, jobData);

if (result.ok) {
// Success - redirect to job posting
middleware.redirect('/jobs/' + result.value.id);
} else {
// Handle business logic errors
setError(result.error.message);
}
} catch (error) {
// Handle network/unexpected errors
setError('Something went wrong');
}
};

Job Application Flow

function JobApplicationButton({ middleware, state, jobId, organizationId }) {
const handleApply = () => {
if (middleware.isLoggedIn()) {
// User is authenticated - create application
const applicationData = { jobId, coverLetter: state.coverLetter };
middleware.onCreateOrder(organizationId, applicationData);
} else {
// Redirect to login
middleware.redirect('/login');
}
};

return (
<button onClick={handleApply}>
Apply for Job
</button>
);
}

Real-time Messaging Setup

useEffect(() => {
if (middleware.isLoggedIn() && currentUserId) {
// Subscribe to real-time notifications and messages
middleware.onSocketSubscribeToUserId(
currentUserId,
(error) => console.error('Socket error:', error),
(message) => {
// Handle incoming message
console.log('New message:', message);
}
);

// Cleanup on unmount
return () => {
middleware.onSocketUnSubscribeToUserId(currentUserId);
};
}
}, [currentUserId]);

💡 Best Practices

Async/Await Pattern

  • Always use async/await with middleware functions that return promises
  • Handle both success and error cases explicitly
  • Use try/catch blocks for unexpected errors

Result Pattern

  • Check the ok property before accessing result.value
  • Handle result.error appropriately for user feedback
  • Never assume success without checking the result status

State Management

  • Use middleware functions instead of direct API calls
  • Allow middleware to handle state updates automatically
  • Use updateState sparingly for custom state modifications

Error Handling

  • Provide user-friendly error messages for UI feedback
  • Log detailed errors for debugging purposes
  • Implement retry mechanisms for network-related errors

Real-time Communication

  • Always provide error and message handlers for socket subscriptions
  • Clean up subscriptions on component unmount to prevent memory leaks
  • Handle connection state changes gracefully