A comprehensive toolkit for rapidly building SaaS applications with React, Firebase, and Redux.
npm install greencode-saas-factoryA comprehensive toolkit for rapidly building SaaS applications with React, Firebase, and Redux.
``bash`
npm install greencode-saas-factory
A fully customizable authentication component that handles:
- Login
- Signup
- Password Reset
- Custom signup fields
`typescript
import { Authentication } from 'greencode-saas-factory';
function App() {
return (
// Handle login
}}
onSignup={async (email, password, data) => {
// Handle signup
}}
onForgotPassword={async (email) => {
// Handle password reset
}}
// Customization options
logo={
headerText="Welcome"
customSignupFields={[
{
key: "company",
label: "Company Name",
type: "text",
placeholder: "Enter company name"
}
]}
// Feature flags
showLogin={true}
showSignup={true}
showForgotPassword={true}
/>
);
}
`
#### Normalized Service
Handles individual documents with optimal querying and caching:
`typescript
import { NormalizedService } from 'greencode-saas-factory';
// Initialize
const userService = new NormalizedService(firestore, 'users');
// CRUD Operations
await userService.create({ name: 'John', email: 'john@example.com' });
await userService.getById('userId');
await userService.update('userId', { name: 'John Doe' });
await userService.delete('userId');
// Advanced Querying
await userService.getAll({
where: [{ field: 'status', operator: '==', value: 'active' }],
orderBy: [{ field: 'createdAt', direction: 'desc' }],
limitTo: 10
});
`
#### Denormalized Service
Handles collections with array-based storage (optimal for bulk operations):
`typescript
import { DenormalizedService } from 'greencode-saas-factory';
// Initialize
const service = new DenormalizedService(firebaseConfig);
// Array Operations
await service.setDocument('collection', 'docId', items);
await service.addItem('collection', newItem);
await service.updateItem('collection', 'docId', 'itemId', updates);
await service.deleteItem('collection', 'docId', 'itemId');
// Querying
await service.queryDocuments('collection', {
filters: [{ field: 'status', operator: '==', value: 'active' }],
limit: 10
});
`
Pre-configured Redux slices for common SaaS functionalities:
#### Authentication State
`typescript
import {
loginStart,
loginSuccess,
loginFailure,
selectUser,
selectIsAuthenticated
} from 'greencode-saas-factory';
// Dispatch actions
dispatch(loginStart());
dispatch(loginSuccess(userData));
dispatch(loginFailure(error));
// Select state
const user = useSelector(selectUser);
const isAuthenticated = useSelector(selectIsAuthenticated);
`
#### Data Management
`typescript
import {
fetchStart,
fetchSuccess,
fetchFailure,
selectData
} from 'greencode-saas-factory';
// Dispatch actions
dispatch(fetchStart());
dispatch(fetchSuccess(data));
dispatch(fetchFailure(error));
// Select state
const data = useSelector(selectData);
`
#### Form Management
`typescript
import {
setFormData,
clearFormData,
setFormError,
selectFormData,
selectFormErrors
} from 'greencode-saas-factory';
// Dispatch actions
dispatch(setFormData({ field: value }));
dispatch(setFormError({ field: 'error message' }));
// Select state
const formData = useSelector(selectFormData);
const formErrors = useSelector(selectFormErrors);
`
#### UI State
`typescript
import {
openModal,
closeModal,
showNotification,
selectModalOpen,
selectNotification
} from 'greencode-saas-factory';
// Dispatch actions
dispatch(openModal('modalName'));
dispatch(showNotification({ message: 'Success!', type: 'success' }));
// Select state
const isModalOpen = useSelector(selectModalOpen);
const notification = useSelector(selectNotification);
`
Customize your application's theme:
`typescript
import { getTheme } from 'greencode-saas-factory';
// Get default theme or customize
const theme = getTheme({
// Your theme overrides
});
`
1. Data Structure: Choose between NormalizedService and DenormalizedService based on your data needs:
- Use NormalizedService for individual documents with complex queries
- Use DenormalizedService for bulk operations and array-based storage
2. State Management: Utilize the provided Redux slices for consistent state management across your application
3. Authentication: Leverage the Authentication component's customization options to match your brand and requirements
4. Performance: Both services include built-in caching and optimization strategies for better performance
This package provides a solid foundation for building modern SaaS applications with React and Firebase, handling common concerns like authentication, data management, and state management out of the box.
UI
`tsx
interface CrudFormProps
fields: FormField
onSubmit: (values: T) => Promise
crud: UseCrudReturn
csrfToken: string;
enableHistory?: boolean;
// ... other props
}
// Usage
fields={[
{
name: 'email',
type: 'email',
validation: [{
test: (v) => /@company\.com$/.test(v),
message: "Company email required"
}]
}
]}
onSubmit={handleSubmit}
crud={crud}
csrfToken={csrfToken}
/>
`
Key Features:
- Input sanitization & XSS protection
- Cross-field dependency management
- Undo/redo history stack
- CSRF token validation
- Zod schema integration
- Error boundaries & accessibility
---
`tsx
interface CrudTableProps
columns: Array
data: D[];
serverSideTotal: number;
userRole?: string;
// ... other props
}
// Usage
columns={[
{
Header: 'Name',
accessor: 'name',
permission: 'admin',
filter: 'text'
}
]}
data={users}
serverSideTotal={1000}
userRole="admin"
/>
`
Key Features:
- Virtualized rendering with react-window
- Role-based column permissions
- Server-side pagination
- Customizable filters
- Row selection & batch operations
- Audit logging integration
---
`tsx`
onClose={close}
mode="delete"
title="Confirm Deletion"
contentSecurityPolicy="default-src 'self'"
onOpenTrack={analytics.trackModalOpen}
>
Security Features:
- CSP support
- Focus management
- Glassmorphism effect
- Motion presets
- Error context logging
- XSS-safe content rendering
---
`tsx`
label="Password"
showCharacterCount
sanitize={sanitizePassword}
validation={passwordValidations}
/>
Features:
- Password strength meter
- Input masking
- Character counter
- Clipboard sanitization
- Floating labels
- Cross-browser consistency
---
`tsx`
const {
data,
errors,
performAction,
trackChange,
undo,
redo,
auditLog,
handleVersionConflict
} = useCrud
validationSchema: UserSchema,
csrfTokenEndpoint: '/api/csrf'
});
Methods:
- performAction() - CSRF-protected operationstrackChange()
- - Audit-logged mutationsapplyOptimisticUpdate()
- - UI-first updates
- Conflict resolution system
- Versioned undo/redo
---
ts
// Automatic token handling
const refreshCsrfToken = async () => {
const encrypted = await encryptToken(rawToken);
document.cookie = XSRF-TOKEN=${encrypted}; Secure; HttpOnly;
return encrypted;
};
`Features:
- SHA-256 token encryption
- Automatic cookie management
- Header injection
- Token refresh queue
- Error recovery
---
$3
`ts
const sanitizeInput = (input: string, options?: SanitizeOptions) => {
return DOMPurify.sanitize(input, {
ALLOWED_TAGS: [],
FORBID_ATTR: ['style', 'onclick']
});
};
`Protections:
- XSS prevention
- Attribute whitelisting
- Pattern filtering
- Length restrictions
- DOM injection protection
---
5. Performance Features
$3
`tsx
height={600}
itemCount={rows.length}
itemSize={getRowHeight}
width="100%"
/>
`Optimizations:
- Dynamic row height calculation
- Windowed rendering
- Memoized columns
- GPU-accelerated scrolling
- Mobile-responsive layout
---
$3
`ts
// Optimistic updates
const applyOptimisticUpdate = (update: Partial) => {
setState(prev => ({
versionNumber: prev.versionNumber + 1,
auditLog: [...prev.auditLog, newEntry]
}));
};
`Features:
- Version conflict detection
- Atomic state transitions
- Throttled validation
- Auto-save functionality
- Compressed history storage
---
6. Audit & Monitoring
$3
`ts
interface AuditEntry {
timestamp: Date;
action: 'CREATE' | 'UPDATE' | 'DELETE';
details: string;
version: number;
}
`Tracking:
- User actions
- Validation errors
- CSRF events
- Version changes
- Conflict resolutions
- Performance metrics
---
7. Error Handling
$3
`tsx
FallbackComponent={({ error, reset }) => (
)}
>
`Features:
- Contextual error messages
- Recovery mechanisms
- Error code taxonomy
- Stack trace preservation
- Localization support
---
8. Best Practices
$3
`ts
// Secure cookie settings
document.cookie = XSRF-TOKEN=${token}; ;
`Recommendations:
- Always validate CSRF tokens
- Use Content Security Policies
- Sanitize all user inputs
- Implement role-based access
- Encrypt sensitive data
- Regular security audits
---
$3
`ts
// Virtualization config
const setRowHeight = useCallback((index: number, height: number) => {
rowHeights.current[index] = height;
listRef.current?.resetAfterIndex(index);
}, []);
``Optimization Tips:
- Use windowing for large datasets
- Memoize expensive calculations
- Throttle validation
- Optimize re-renders
- Use compression
- Implement caching
---
This documentation covers the core aspects of the Greencode SaaS Factory. For detailed implementation guides and advanced use cases, refer to our interactive storybook documentation.