Blog

Gate a Next.js feature with Subscrio in ixartz's SaaS Boilerplate

A Next.js server route checks a Clerk organization’s paid feature with Subscrio before returning protected data.

Subscrio lets an application check which features a customer can use without putting plan rules in every route. In ixartz’s Next.js SaaS Boilerplate, use Clerk’s active organization ID as the customer key, define a feature and its plan value once, then ask Subscrio at the server action that needs the answer.

This example gates a report export. Clerk still decides whether the signed-in user may perform the action; Subscrio decides whether the organization’s plan includes it. Those checks answer different questions.

1. Add a server-only Subscrio client

The boilerplate uses Next.js, TypeScript, Clerk organizations, and PostgreSQL. Its free edition does not include a billing integration, so this guide uses a verified subscription event as the point where your chosen billing provider connects a customer to a Subscrio plan.

From the boilerplate root, install the library:

npm install subscrio

Create src/libs/Subscrio.ts:

import 'server-only';
import { Subscrio, loadConfig } from 'subscrio';

export const subscrio = new Subscrio(loadConfig());

The TypeScript package reads its PostgreSQL connection string from DATABASE_URL. Use the same database configuration as the application, and keep this client in server-side code; do not import it into a client component. The library stores its feature and subscription records in PostgreSQL through the configured DATABASE_URL.

2. Define a feature and the value included in a plan

Set up the catalog once in an administrative script or deployment task. This example creates a report-export feature that is off by default and on for the team-monthly plan.

import { Subscrio, loadConfig } from 'subscrio';

const subscrio = new Subscrio(loadConfig());

try {
  if (await subscrio.verifySchema()) {
    await subscrio.migrate();
  } else {
    await subscrio.installSchema();
  }

  await subscrio.products.createProduct({
    key: 'workspace',
    displayName: 'Workspace',
  });

  await subscrio.features.createFeature({
    key: 'report-export',
    displayName: 'Export reports',
    valueType: 'toggle',
    defaultValue: 'false',
  });

  await subscrio.products.associateFeature('workspace', 'report-export');

  await subscrio.plans.createPlan({
    key: 'team',
    productKey: 'workspace',
    displayName: 'Team',
  });

  await subscrio.plans.setFeatureValue('team', 'report-export', 'true');

  await subscrio.billingCycles.createBillingCycle({
    key: 'team-monthly',
    planKey: 'team',
    displayName: 'Monthly',
    durationValue: 1,
    durationUnit: 'months',
  });
} finally {
  await subscrio.close();
}

The stable keys (workspace, report-export, and team-monthly) are what application code uses. Display names are for people. Run this setup once per environment; do not create catalog records during each page request.

3. Connect a verified customer subscription to the plan

For a team application, members of the same Clerk organization usually share one plan. Use the active organization ID returned by Clerk’s server-side auth(); never accept the customer key or plan key from a browser form.

After your billing provider verifies a subscription event and maps its price to team-monthly, create or update the Subscrio subscription from trusted server code:

import 'server-only';
import { subscrio } from '@/libs/Subscrio';

export async function applyVerifiedTeamSubscription(input: {
  organizationId: string;
  providerSubscriptionId: string;
}) {
  const customerKey = input.organizationId;
  const subscriptionKey = `billing_${input.providerSubscriptionId}`;

  const customer = await subscrio.customers.getCustomer(customerKey);
  if (!customer) {
    await subscrio.customers.createCustomer({
      key: customerKey,
      displayName: customerKey,
    });
  }

  const existing = await subscrio.subscriptions.getSubscription(subscriptionKey);
  if (existing) {
    return subscrio.subscriptions.updateSubscription(subscriptionKey, {
      billingCycleKey: 'team-monthly',
    });
  }

  return subscrio.subscriptions.createSubscription({
    key: subscriptionKey,
    customerKey,
    billingCycleKey: 'team-monthly',
  });
}

Call this function only after the provider has verified the webhook signature and you have confirmed the current subscription is active. In a real integration, map the provider’s verified price ID to a Subscrio billing-cycle key on the server. Handle cancellation and renewal from the provider’s current subscription state as well. Do not let an unverified or out-of-order event grant access.

4. Check the feature where the protected action runs

This route checks the signed-in user, the selected organization, the application’s organization-admin role, and the plan feature separately. The organization ID comes from Clerk’s server-side session, not from request JSON.

Create src/app/api/reports/export/route.ts:

import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import { subscrio } from '@/libs/Subscrio';

export async function POST() {
  const { isAuthenticated, orgId, orgRole } = await auth();

  if (!isAuthenticated) {
    return NextResponse.json({ error: 'Sign in required' }, { status: 401 });
  }
  if (!orgId) {
    return NextResponse.json({ error: 'Choose an organization' }, { status: 400 });
  }
  if (orgRole !== 'org:admin') {
    return NextResponse.json({ error: 'Organization admin required' }, { status: 403 });
  }

  const canExportReports = await subscrio.featureChecker.isEnabledForCustomer(
    orgId,
    'workspace',
    'report-export',
  );

  if (!canExportReports) {
    return NextResponse.json(
      { error: 'Report export is not included in this plan' },
      { status: 403 },
    );
  }

  const csv = [`organization_id,generated_at`, `${orgId},${new Date().toISOString()}`].join('\n');

  return new Response(csv, {
    headers: {
      'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': 'attachment; filename="report.csv"',
    },
  });
}

This sample returns a small CSV so the route is executable without needing sample business data. In your application, replace those two sample columns with the report query you already have and scope every row to orgId. The access decision remains the server-side isEnabledForCustomer(customerKey, productKey, featureKey) call: without an active plan that enables export, the route stops before returning the file.

To make a customer-specific exception, grant an override from a trusted administrative flow:

await subscrio.subscriptions.addFeatureOverride(
  subscriptionKey,
  'report-export',
  'true',
);

That changes the feature value for the selected subscription. Your application must still decide who may grant the exception and how it should be reviewed or removed.

What belongs in each layer

  • Clerk: who signed in, which organization is active, and what role the member has.
  • Your billing provider: whether payment is current and which purchased price applies.
  • Subscrio: the feature values attached to the customer’s active plan, plus any subscription-specific override.
  • The Next.js route: whether this user may perform the action and the application work that follows.

The route calls Subscrio at the point of use, so the feature rule stays out of client-side code and beside the operation it protects. A disabled button can improve the interface, but the server route remains the access boundary.

Sources

Written by

Jasen Fici

Founder, Subscrio

Bootstrapped founder. Built Velaro and StatusCast. Now building Subscrio, an entitlement engine for software products.

Screenshot preview