Skip to main content
Photo from unsplash: thesawraj/blogs/tech/upfgqhskhrye9m1s8mcd

Introducing @alpha07/time-control: A Powerful Time-Based Access Control for React Apps

Written on March 18, 2025 by alpha.

4 min read
––– views
Read in Hindi

🚀 Overview

I'm excited to introduce my first npm package: @alpha07/time-control, a powerful React component for implementing time-based access control in frontend applications. This package is ideal for managing trial periods, subscriptions, and access restrictions while ensuring security and flexibility.

🎯 Why I Built This Package

In many SaaS applications, handling trial periods and subscriptions securely can be challenging. Existing solutions often lack customization or require complex backend implementations. I wanted to create an easy-to-use, frontend-based solution that:

  • Tracks user access duration securely
  • Provides tamper-resistant storage
  • Supports remote configuration and customization
  • Works with minimal setup

Thus, @alpha07/time-control was born! 🎉


🛠️ Installation

Getting started is easy. Simply install the package using npm or yarn:

npm install @alpha07/time-control

or

yarn add @alpha07/time-control

🔥 Quick Start

Basic Implementation

The simplest way to use TimeAccessControl is by adding it inside your React app:

import { TimeAccessControl } from '@alpha07/time-control';
 
function App() {
  return (
    <>
      <TimeAccessControl
        expiryDays={7}
        secretKey="your-secure-key"
      />
      <YourAppContent />
    </>
  );
}

This ensures that the user has access for 7 days, after which the app will display a trial expiration message.


✨ Features

🔒 Secure Time Tracking

  • AES encryption for storing trial information
  • Tamper-resistant implementation
  • Domain validation to prevent unauthorized usage

🌐 Remote Management

  • Dynamic configuration via API
  • Remote kill switch to disable access if needed
  • Custom messaging for users

🛡️ Robust Error Handling

  • Multiple fallback modes (block, warn, allow)
  • Graceful degradation if local storage is inaccessible
  • Automatic recovery to handle unexpected errors

🎨 Highly Customizable

  • Custom overlay components for expired trials
  • Styling options for a seamless user experience
  • Event callbacks for tracking user behavior

📖 Usage Examples

Advanced Implementation with Remote Control

For a more dynamic approach, TimeAccessControl can fetch trial settings remotely:

import { TimeAccessControl } from 'time-control';
 
function App() {
  const handleExpiry = () => {
    analytics.track('trial_expired');
    showUpgradeModal();
  };
 
  return (
    <div>
      <TimeAccessControl
        remoteConfigUrl="https://api.example.com/access-config"
        fallbackMode="warn"
        onExpiry={handleExpiry}
        secretKey={process.env.REACT_APP_ACCESS_KEY}
        customComponent={
          <div className="custom-paywall">
            <h2>Trial Expired</h2>
            <button onClick={handleUpgrade}>Upgrade Now</button>
          </div>
        }
      />
      <YourAppContent />
    </div>
  );
}

This allows you to dynamically control trial duration, messages, and allowed domains from a remote API.


🔧 Configuration Options

PropTypeDefaultDescription
expiryDaysnumber7Duration of the trial period
messagestring"Trial period..."Message displayed on expiry
backgroundColorstring"#ffffff"Overlay background color
textColorstring"#000000"Overlay text color
secretKeystringRequiredEncryption key
remoteConfigUrlstringundefinedURL for remote config
fallbackMode`'block''warn''allow'`
onExpiry() => voidundefinedCallback when trial expires
customComponentReactNodeundefinedCustom overlay component

🔐 Security Best Practices

1. Secure Key Management

Never expose your secret key in the frontend:

// ❌ BAD: Hardcoding secret keys
const secretKey = "1234567890";
 
// ✅ GOOD: Using environment variables
const secretKey = process.env.REACT_APP_ACCESS_KEY;

2. Domain Validation

Restrict trial usage to specific domains:

{
  "allowedDomains": [
    "yourdomain.com",
    "app.yourdomain.com",
    "staging.yourdomain.com"
  ]
}

3. Error Handling

Handle expiry events gracefully:

<TimeAccessControl
  fallbackMode="warn"
  onExpiry={() => {
    analytics.track('trial_expired');
    showUpgradeModal();
  }}
/>

📦 API Reference

Utility Functions

Reset Timer

Manually resets the trial period:

import { resetTimer } from 'time-control';
 
function handleSubscriptionPurchase() {
  if (resetTimer('trial-storage', 'secure-key')) {
    console.log('Trial reset successfully');
  }
}

Get Remaining Time

Fetch the remaining trial period in days:

import { getTimeRemaining } from 'time-control';
 
function DisplayTimeRemaining() {
  const daysLeft = getTimeRemaining('trial-storage', 'secure-key', 30);
  return <p>{daysLeft > 0 ? `${daysLeft.toFixed(1)} days remaining` : 'Trial expired'}</p>;
}

🤝 Contributing

I welcome contributions! If you have feature requests, bug reports, or improvements, feel free to submit a PR or open an issue on GitHub.


📄 License

@alpha07/time-control is open-source and licensed under the MIT License.

Install Now: npm i @alpha07/time-control 🚀

For any questions or feedback, reach out to me. Happy coding! 🎉

Share this article

Enjoying this post?

Don't miss out 😉. Get an email whenever I post, no spam.

Subscribe Now