Real SaaS API Workflow
Real SaaS API Workflow combines routing, services, auth, protected routes, loading and error states, and feature organization into an order-management product flow.
Course: React — Routing & API Integration Lesson: 15
Learning objectives
Combine routing, API services, authentication, protected routes, loading and error states, pagination, and feature-level organization into a realistic SaaS workflow.
Scenario: Order management SaaS
Build a workspace where authenticated users can:
- View an order list.
- Search and filter orders.
- Open an order detail page.
- Create an order.
- See loading, empty, and error states.
- Access only the features permitted by their account.
- Navigate directly to a bookmarked order URL.
Suggested feature structure
src/app/App.jsxrouter.jsxproviders/AuthProvider.jsxfeatures/orders/components/OrderList.jsxOrderFilters.jsxOrderDetails.jsxOrderForm.jsxhooks/useOrders.jsuseOrderDetails.jsservices/orderService.jspages/OrdersPage.jsxOrderDetailsPage.jsxshared/api/apiClient.jscomponents/LoadingState.jsxErrorState.jsxNotFoundState.jsx
Keep business-domain code together. Shared infrastructure should contain genuinely reusable concerns, not every feature-specific helper.
Define the API contract first
Before writing UI code, document endpoints and response shapes. Example contract:
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/orders?page=1 | List orders |
| GET | /api/orders/:id | Order detail |
| POST | /api/orders | Create order |
| PATCH | /api/orders/:id | Update supported fields |
Document authentication requirements, permission requirements, pagination metadata, validation errors, and status codes. The table is illustrative; the actual backend contract is authoritative.
Build the service layer
import { apiClient } from "../../shared/api/apiClient";export async function listOrders(params) {const response = await apiClient.get("/orders", { params });return response.data;}export async function getOrder(orderId, config = {}) {const response = await apiClient.get(`/orders/${encodeURIComponent(orderId)}`,config);return response.data;}export async function createOrder(payload) {const response = await apiClient.post("/orders", payload);return response.data;}
Services own endpoint details. They should not decide whether the UI shows a spinner or toast.
Compose the route hierarchy
<Routes><Route path="/login" element={<LoginPage />} /><Route element={<RequireAuth />}><Route path="/workspace" element={<WorkspaceLayout />}><Route index element={<DashboardPage />} /><Route path="orders" element={<OrdersPage />} /><Route path="orders/:orderId" element={<OrderDetailsPage />} /></Route></Route></Routes>
The shared workspace layout remains visible while the nested page changes. The route guard waits for authentication state and protects the UI.
Implement the list workflow
The Orders page owns user-facing filters and pagination state, while a feature hook coordinates data retrieval. The service performs HTTP communication. The view renders loading, error, empty, and populated states.
OrdersPage|vuseOrders(filters, page)|vorderService.listOrders()|vBackend API|v{ items, page, totalPages }|vOrderTable
For production, use request cancellation or a query library to prevent stale responses and manage caching.
Implement details workflow
The dynamic :orderId route supplies the identifier through useParams. Validate its format if the domain has a defined format, fetch the resource, and show a not-found state for a missing order. The backend must verify that the current user can access that specific order.
Create-order mutation
On submit:
- Validate the form.
- Disable duplicate submission while pending.
- Call the create service.
- Display field-level validation errors when provided.
- On success, invalidate or refresh the order list.
- Navigate to the new order detail page.
- Show a success notification.
Do not trigger the mutation indirectly by setting a flag and watching it in an Effect. The submit event is the natural place for a user-triggered create operation.
Production readiness checklist
- API contract and error mapping are documented.
- Authentication restoration is handled before protected content renders.
- Backend enforces tenant and resource permissions.
- Deep links work after refresh.
- Loading, empty, error, and success states are designed.
- Search is debounced where appropriate.
- Pagination is server-side for large datasets.
- Obsolete requests are cancelled or ignored.
- Cache keys include user/tenant scope.
- Logout clears user-specific data.
- Mutations prevent accidental duplicate submission.
- Sensitive information is not logged.
- Tests cover route access and API failure cases.
- Monitoring captures request latency and failure rates.
Common mistakes
- Putting routing, authentication, fetching, and all page UI in one component.
- Duplicating API paths across components.
- Assuming a protected route secures the API.
- Ignoring tenant boundaries in cache keys.
- Refreshing the entire page after every mutation.
- Showing raw backend errors to customers.
- Releasing without testing deep links and session expiry.
Interview questions & answers
Interview preparation
7 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1Walk through the architecture of an enterprise order-management feature.
BeginnerModel answer
Routes define workspace navigation; auth guards protect UI; feature hooks coordinate list/detail/create flows; services own HTTP; views render loading/empty/error/success while the backend enforces permissions.
2How do you handle stale search responses?
BeginnerModel answer
Debounce input, cancel or ignore obsolete requests, and only apply results that match the latest filters.
3What would you monitor after deployment?
BeginnerModel answer
Request latency, failure rates, auth/session errors, deep-link success, and user-perceived loading for critical order workflows.
Intermediate
4Where should API endpoint logic live?
IntermediateModel answer
In a feature or shared service layer—not scattered across presentational components—so paths, headers, and parsing stay centralized.
5How do you invalidate cached order data after a mutation?
IntermediateModel answer
On successful create/update, invalidate or refresh list/detail cache keys for that tenant/user scope so UI reflects the new server state.
Advanced
6How do route guards interact with authentication restoration?
AdvancedModel answer
Guards wait while auth status ischecking, then allowOutletor redirect to login so protected content does not flash incorrectly.7How do you enforce tenant isolation?
AdvancedModel answer
Include tenant/user scope in cache keys and API requests, and rely on backend authorization so one tenant cannot read another’s resources.
Capstone exercise
Implement the order workflow end to end using a mock or real API. Include login, protected workspace routes, nested layouts, dynamic order details, search, pagination, create-order mutation, notifications, and resilient loading/error states. Add unit tests for services and hooks, plus integration tests for navigation and access control.