Supabase

How to Build Subscription Management with Supabase

Discover step-by-step guidance on building a subscription management system using Supabase, enhancing your app's functionality with ease and efficiency.

Developer profile skeleton
Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to Build Subscription Management with Supabase

 

1. Set Up Your Supabase Project

 

  • Go to the Supabase website and log in or create an account if you don't have one.
  • Create a new project by clicking on the "New Project" button and following the prompts.
  • Note down the project URL and the API keys provided; you'll need these in later steps.
  • Enable Database and Auth features in your project settings if they are not already enabled.

 

2. Initialize Your Database

 

  • Once the project is created, go to the "Database" section in the Supabase dashboard.
  • Click on "Table Editor" and create a new table called "subscriptions".
  • Add the following fields to the table:
    • id (primary key, type: uuid, default: gen_random_uuid())
    • user\_id (type: uuid, foreign key referencing the users table)
    • plan (type: text)
    • status (type: text)
    • valid\_until (type: timestamp)

 

3. Install Supabase Client Library

 

  • If you're using Node.js, run npm install @supabase/supabase-js
  • If you're using other environments like React or Angular, install the appropriate supabase client library as per your environment.

 

4. Initialize Supabase Client

 

  • In your project, import and initialize the Supabase client:
    import { createClient } from '@supabase/supabase-js';
    
    

    const supabaseUrl = 'YOUR_SUPABASE_URL';
    const supabaseKey = 'YOUR_SUPABASE_KEY';
    const supabase = createClient(supabaseUrl, supabaseKey);


 

5. Implement Signup and Login Functionality

 

  • Use Supabase's Auth API for signing up and logging in users:
    // Sign up
    const { user, session, error } = await supabase.auth.signUp({
      email: '[email protected]',
      password: 'your-password'
    });
    
    

    // Log in
    const { user, session, error } = await supabase.auth.signIn({
    email: 'user@example.com',
    password: 'your-password'
    });


 

6. Create Subscription Logic

 

  • Write a function to handle user subscriptions:
    async function createSubscription(userId, plan) {
      const { data, error } = await supabase
        .from('subscriptions')
        .insert([
          { user_id: userId, plan: plan, status: 'active', valid_until: new Date(new Date().setMonth(new Date().getMonth() + 1)) }
        ]);
    
    

    if (error) throw error;
    return data;
    }


 

7. Manage Subscription Status

 

  • To manage subscription status, update the subscription based on certain criteria:
    async function updateSubscriptionStatus(userId, status) {
      const { data, error } = await supabase
        .from('subscriptions')
        .update({ status: status })
        .eq('user\_id', userId);
    
    

    if (error) throw error;
    return data;
    }


 

8. Implement Middleware for Protected Routes

 

  • To protect certain routes, create middleware to check user authentication:
    function requireAuth(req, res, next) {
      const session = supabase.auth.session();
      if (!session) {
        return res.status(401).send('Unauthorized');
      }
      req.user = session.user;
      next();
    }

 

9. Frontend (Optional)

 

  • Implement the frontend to let users select subscription plans and manage their subscriptions:
    // Example code to display subscription plans
    const plans = ['Basic', 'Premium', 'Pro'];
    
    

    plans.forEach(plan => {
    const button = document.createElement('button');
    button.innerText = plan;
    button.onclick = async () => {
    const user = supabase.auth.user();
    if (user) {
    await createSubscription(user.id, plan);
    alert('Subscription created successfully!');
    } else {
    alert('You need to be logged in to subscribe.');
    }
    };
    document.body.appendChild(button);
    });


 

10. Maintain Subscription

 

  • Implement a background job or cron job to check subscription validity and update status accordingly:
  • Example: Node.js with node-cron
    const cron = require('node-cron');
    
    

    cron.schedule('_ _ _ _ *', async () => {
    const { data: subscriptions } = await supabase
    .from('subscriptions')
    .select('*')
    .eq('status', 'active');

    subscriptions.forEach(async subscription => {
    if (new Date(subscription.valid_until) < new Date()) {
    await updateSubscriptionStatus(subscription.user_id, 'expired');
    }
    });
    });


Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.