npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

greencode-saas-factory

v1.2.27

Published

A comprehensive toolkit for rapidly building SaaS applications with React, Firebase, and Redux.

Readme

Greencode SaaS Factory Documentation

A comprehensive toolkit for rapidly building SaaS applications with React, Firebase, and Redux.

Installation

npm install greencode-saas-factory

Core Features

1. Authentication Component

A fully customizable authentication component that handles:

  • Login
  • Signup
  • Password Reset
  • Custom signup fields
import { Authentication } from 'greencode-saas-factory';

function App() {
  return (
    <Authentication
      onLogin={async (email, password) => {
        // Handle login
      }}
      onSignup={async (email, password, data) => {
        // Handle signup
      }}
      onForgotPassword={async (email) => {
        // Handle password reset
      }}
      // Customization options
      logo={<YourLogo />}
      headerText="Welcome"
      customSignupFields={[
        {
          key: "company",
          label: "Company Name",
          type: "text",
          placeholder: "Enter company name"
        }
      ]}
      // Feature flags
      showLogin={true}
      showSignup={true}
      showForgotPassword={true}
    />
  );
}

2. Firebase Data Services

Normalized Service

Handles individual documents with optimal querying and caching:

import { NormalizedService } from 'greencode-saas-factory';

// Initialize
const userService = new NormalizedService(firestore, 'users');

// CRUD Operations
await userService.create({ name: 'John', email: '[email protected]' });
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):

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
});

3. Redux Integration

Pre-configured Redux slices for common SaaS functionalities:

Authentication State

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

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

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

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);

Theme Support

Customize your application's theme:

import { getTheme } from 'greencode-saas-factory';

// Get default theme or customize
const theme = getTheme({
  // Your theme overrides
});

Best Practices

  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

1. Core Components

1.1 CrudForm

A dynamic form component with validation, history, and security features.

interface CrudFormProps<T> {
  fields: FormField<T>[];
  onSubmit: (values: T) => Promise<void>;
  crud: UseCrudReturn<T>;
  csrfToken: string;
  enableHistory?: boolean;
  // ... other props
}

// Usage
<CrudForm<User>
  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

1.2 CrudTable

Virtualized table with enterprise-grade features.

interface CrudTableProps<D> {
  columns: Array<CustomColumn<D>>;
  data: D[];
  serverSideTotal: number;
  userRole?: string;
  // ... other props
}

// Usage
<CrudTable<User>
  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

1.3 CrudModal

Animated modal system with security tracking.

<CrudModal
  isOpen={isOpen}
  onClose={close}
  mode="delete"
  title="Confirm Deletion"
  contentSecurityPolicy="default-src 'self'"
  onOpenTrack={analytics.trackModalOpen}
>
  <DeleteConfirmation />
</CrudModal>

Security Features:

  • CSP support
  • Focus management
  • Glassmorphism effect
  • Motion presets
  • Error context logging
  • XSS-safe content rendering

2. Form Components

2.1 FormInput

Secure input component with advanced features.

<FormInput
  type="password"
  label="Password"
  showCharacterCount
  sanitize={sanitizePassword}
  validation={passwordValidations}
/>

Features:

  • Password strength meter
  • Input masking
  • Character counter
  • Clipboard sanitization
  • Floating labels
  • Cross-browser consistency

3. State Management

3.1 useCrud Hook

Central state manager for CRUD operations.

const {
  data,
  errors,
  performAction,
  trackChange,
  undo,
  redo,
  auditLog,
  handleVersionConflict
} = useCrud<User>(initialData, {
  validationSchema: UserSchema,
  csrfTokenEndpoint: '/api/csrf'
});

Methods:

  • performAction() - CSRF-protected operations
  • trackChange() - Audit-logged mutations
  • applyOptimisticUpdate() - UI-first updates
  • Conflict resolution system
  • Versioned undo/redo

4. Security System

4.1 CSRF Protection

// 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

4.2 Input Sanitization

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

5.1 Virtualized Table

<VariableSizeList
  height={600}
  itemCount={rows.length}
  itemSize={getRowHeight}
  width="100%"
/>

Optimizations:

  • Dynamic row height calculation
  • Windowed rendering
  • Memoized columns
  • GPU-accelerated scrolling
  • Mobile-responsive layout

5.2 State Management

// Optimistic updates
const applyOptimisticUpdate = (update: Partial<T>) => {
  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

6.1 Audit Logging

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

7.1 Error Boundaries

<ErrorBoundary
  FallbackComponent={({ error, reset }) => (
    <ErrorFallback error={error} locale={locale} />
  )}
>
  <CrudForm {...props} />
</ErrorBoundary>

Features:

  • Contextual error messages
  • Recovery mechanisms
  • Error code taxonomy
  • Stack trace preservation
  • Localization support

8. Best Practices

8.1 Security

// Secure cookie settings
document.cookie = `XSRF-TOKEN=${token}; 
  Secure; 
  HttpOnly; 
  SameSite=Strict;
  Path=/;
  Max-Age=86400`;

Recommendations:

  • Always validate CSRF tokens
  • Use Content Security Policies
  • Sanitize all user inputs
  • Implement role-based access
  • Encrypt sensitive data
  • Regular security audits

8.2 Performance

// 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.