Next.js / 16 min read

Build an Inventory Management System with Next.js and Supabase

Build an inventory management system with Next.js and Supabase. Learn PostgreSQL stock tracking, secure RLS policies, and safe inventory updates. Copy

No reproducible test record has been approved for this published version. Check its commands against your software versions before using them.

How we verify guides
Build an Inventory Management System with Next.js and Supabase
On this page

Inventory management becomes surprisingly complicated when more than one person can update stock.

Imagine a small electronics store with one laptop left in stock. Two employees open the inventory dashboard, and both see the same available quantity. A few seconds later, both attempt to sell that laptop.

If the application checks availability in JavaScript and updates stock in a separate request, both sales might be accepted.

The problem isn't the dashboard. It's how the database handles competing transactions.

In this tutorial, we'll design the core of an inventory management system using Next.js, Supabase, and PostgreSQL, with a focus on stock tracking, transaction safety, and database permissions.

We'll cover:

  • Designing product and inventory movement tables
  • Tracking stock changes without losing history
  • Preventing two requests from selling the same last item
  • Restricting database access with Row Level Security (RLS)
  • Recording sales through Supabase RPC
  • Testing concurrent requests and retries
  • Avoiding common inventory architecture mistakes

Scope: This is a focused inventory backend example, not a complete point-of-sale or e-commerce application. The SQL design requires integration testing in a disposable Supabase project before production use.

1. Why build an inventory system with Next.js and Supabase?

Next.js provides the application interface, server-side rendering, and server-side operations.

Supabase supplies the PostgreSQL database, authentication, and database APIs.

Together, they provide a useful foundation for inventory applications without requiring you to build every backend service yourself.

TechnologyPurpose
Next.js App RouterApplication pages and forms
ReactInteractive UI
Supabase AuthUser authentication
PostgreSQLProducts, balances, transactions
Supabase RPCControlled database operations
Row Level SecurityPer-user data access

The most important part is PostgreSQL.

When inventory quantities must remain accurate, the database needs to enforce the rules. A fast frontend cannot compensate for unsafe stock updates.

2. Start with the problem: quantity versus stock history

A basic inventory tutorial often begins with a products table:

sql
create table products (
  id uuid primary key default gen_random_uuid(),
  name text not null,
  sku text unique not null,
  quantity integer not null default 0,
  price numeric(10, 2) not null
);

This design can store the current available quantity.

But consider what happens when the quantity changes from 12 to 7.

Was it caused by five sales? A damaged item? An adjustment? A correction to an earlier purchase?

The current number alone cannot answer those questions.

That's why a useful inventory application should record how stock changes, not just what the latest balance happens to be.

Two common inventory designs

There are two reasonable approaches.

Ledger-only design: Store every stock movement and calculate available quantity by summing the changes.

Balance-plus-ledger design: Keep a current stock balance for efficient reads and record every change in a separate movement table.

Neither approach is automatically superior.

A balance-plus-ledger design can make frequent stock lookups simpler, but both records must be updated in the same transaction.

For this tutorial, we'll use the second approach.

3. Design the inventory tables

We'll keep the example intentionally small.

Each product belongs to one authenticated user. A real business application with multiple employees would need a separate organization, membership, and role model.

Create two tables in a disposable Supabase project.

sql
create table public.cwl_inventory_products (
  id uuid primary key default gen_random_uuid(),

  owner_id uuid not null
    references auth.users(id),

  name text not null
    check (char_length(name) between 1 and 200),

  initial_stock integer not null
    check (initial_stock between 0 and 100000),

  stock integer not null
    check (stock between 0 and 100000)
);

create table public.cwl_inventory_movements (
  id uuid primary key default gen_random_uuid(),

  product_id uuid not null
    references public.cwl_inventory_products(id),

  owner_id uuid not null
    references auth.users(id),

  request_id uuid not null,

  delta integer not null
    check (delta between -10000 and -1),

  balance_after integer not null
    check (balance_after >= 0),

  created_at timestamptz not null default now(),

  unique (owner_id, request_id)
);

The first table stores the current balance.

The second records each sale as a negative movement.

For example, suppose a product starts with 10 units.

EventMovementStock remaining
Initial stock—10
Sell 2 units-28
Sell 3 units-35
Sell 1 unit-14

The intended relationship is:

text
Current stock = Initial stock + SUM(movement deltas)

That relationship is called an inventory invariant.

Our sale operation must preserve it.

The example only handles sales. Restocking, refunds, purchase orders, and corrections require additional transaction paths that preserve the same invariant.

4. Understand the inventory race condition

Here's a common mistake:

ts
const { data: product } = await supabase
  .from("products")
  .select("quantity")
  .eq("id", productId)
  .single();

if (product && product.quantity >= requestedQuantity) {
  await supabase
    .from("products")
    .update({
      quantity: product.quantity - requestedQuantity,
    })
    .eq("id", productId);
}

The problem is the gap between reading and updating the quantity.

Imagine two requests running together:

text
Initial stock: 1

Request A reads stock = 1
Request B reads stock = 1

Request A checks availability: PASS
Request B checks availability: PASS

Request A attempts to sell 1
Request B attempts to sell 1

Both requests based their decision on the same earlier value.

The application needs a database operation that checks availability and applies the sale safely.

Why simply adding a PostgreSQL function isn't enough

A database function doesn't automatically prevent race conditions.

For example, attempting to lock an aggregate result using this pattern is incorrect:

sql
-- Incorrect: do not use this as a locking strategy
select sum(delta)
from public.cwl_inventory_movements
where product_id = p_product_id
for update;

PostgreSQL row-locking clauses cannot be used this way on aggregate result rows.

A safer approach is to lock a stable product row and perform the stock update within the database transaction.

5. Restrict database access using Supabase RLS

Before exposing inventory data, we need clear authorization rules.

This simplified example allows an authenticated owner to read their own products and movements.

sql
alter table public.cwl_inventory_products
enable row level security;

alter table public.cwl_inventory_movements
enable row level security;

create policy "Owner can read products"
on public.cwl_inventory_products
for select
to authenticated
using (
  (select auth.uid()) = owner_id
);

create policy "Owner can read movements"
on public.cwl_inventory_movements
for select
to authenticated
using (
  (select auth.uid()) = owner_id
);

A policy is only one part of database authorization.

We must also restrict direct writes.

sql
revoke all on
  public.cwl_inventory_products,
  public.cwl_inventory_movements
from public, anon, authenticated;

grant select on
  public.cwl_inventory_products,
  public.cwl_inventory_movements
to authenticated;

In this model, ordinary clients should not be able to update stock balances or insert movement records directly.

Instead, they call one carefully controlled database function.

Security note: These privileges assume newly created example tables. Existing schemas may have additional column privileges, inherited grants, triggers, or policies that need separate review.

6. Record a sale safely inside PostgreSQL

Now we'll create the sale function.

It has four responsibilities:

  1. Confirm the caller is authenticated and owns the product.
  2. Lock the product row before modifying inventory.
  3. Reject a sale when insufficient stock remains.
  4. Record the movement in the same transaction.

We'll also use a request ID so retrying the same sale does not intentionally create another stock movement.

Important: The following function is a reviewable implementation example. It has not been executed against a live PostgreSQL database for this article. Use it in an isolated test project first.

sql
create or replace function public.cwl_record_sale(
  p_product_id uuid,
  p_qty integer,
  p_request_id uuid
)
returns table (
  remaining_after_sale integer,
  movement_id uuid,
  replayed boolean
)
language plpgsql
security definer
set search_path = ''
as $$
declare
  v_actor uuid := auth.uid();
  v_product public.cwl_inventory_products%rowtype;
  v_previous public.cwl_inventory_movements%rowtype;
  v_remaining integer;
  v_movement uuid;
begin
  if v_actor is null then
    raise exception 'Authentication required'
      using errcode = '42501';
  end if;

  if p_product_id is null
     or p_request_id is null
     or p_qty is null
     or p_qty < 1
     or p_qty > 10000 then
    raise exception 'Invalid sale input'
      using errcode = '22023';
  end if;

  -- Lock the product row owned by this user.
  select p.*
  into v_product
  from public.cwl_inventory_products as p
  where p.id = p_product_id
    and p.owner_id = v_actor
  for update;

  if not found then
    raise exception 'Product unavailable'
      using errcode = '42501';
  end if;

  -- Detect a previously completed request.
  select m.*
  into v_previous
  from public.cwl_inventory_movements as m
  where m.owner_id = v_actor
    and m.request_id = p_request_id;

  if found then
    if v_previous.product_id <> p_product_id
       or v_previous.delta <> -p_qty then
      raise exception 'Request ID reused with different input'
        using errcode = '22023';
    end if;

    return query
    select v_previous.balance_after,
           v_previous.id,
           true;

    return;
  end if;

  -- Update only when enough stock remains.
  update public.cwl_inventory_products as p
  set stock = p.stock - p_qty
  where p.id = p_product_id
    and p.owner_id = v_actor
    and p.stock >= p_qty
  returning p.stock into v_remaining;

  if not found then
    raise exception 'Insufficient stock';
  end if;

  -- Record the corresponding stock movement.
  insert into public.cwl_inventory_movements (
    product_id,
    owner_id,
    request_id,
    delta,
    balance_after
  )
  values (
    p_product_id,
    v_actor,
    p_request_id,
    -p_qty,
    v_remaining
  )
  returning id into v_movement;

  return query
  select v_remaining, v_movement, false;
end;
$$;

Restrict who can execute it:

sql
revoke all on function
public.cwl_record_sale(uuid, integer, uuid)
from public, anon, authenticated;

grant execute on function
public.cwl_record_sale(uuid, integer, uuid)
to authenticated;

Why use SECURITY DEFINER?

The function needs permission to modify tables that regular users cannot update directly.

A SECURITY DEFINER function executes with its owner's privileges.

That also makes it security-sensitive.

It must have a trusted owner, restricted execution permissions, a controlled search path, and explicit authorization checks.

The function above checks auth.uid() and verifies ownership rather than trusting an owner ID supplied by the browser.

Do not deploy it without reviewing those security boundaries in your actual Supabase environment.

What makes the operation transactional?

PostgreSQL executes the statements in the function as part of the calling transaction.

If inserting the movement fails, the exception must be allowed to abort the transaction so the earlier stock reduction is rolled back.

For that reason, avoid swallowing database exceptions and returning a fake success response.

A detail about simultaneous retries

The request ID is unique per owner.

If two attempts reuse that key for different products, the unique constraint may reject one of them.

That failure must roll back its inventory update.

This is one of the scenarios we need to test explicitly before calling the design production-ready.

7. Call the sale function from Next.js

The database owns the inventory rules.

The application submits the request and handles the result.

Here's a small TypeScript helper using an existing authenticated Supabase client.

ts
import type { SupabaseClient } from "@supabase/supabase-js";

type SaleResult = {
  remaining_after_sale: number;
  movement_id: string;
  replayed: boolean;
};

export async function recordSale(
  supabase: SupabaseClient,
  productId: string,
  quantity: number,
  requestId: string
) {
  if (
    !Number.isInteger(quantity) ||
    quantity < 1 ||
    quantity > 10000
  ) {
    throw new Error("Invalid quantity");
  }

  const { data, error } = await supabase.rpc(
    "cwl_record_sale",
    {
      p_product_id: productId,
      p_qty: quantity,
      p_request_id: requestId,
    }
  );

  if (error) {
    throw new Error(error.message);
  }

  const result = data?.[0] as SaleResult | undefined;

  if (
    !result ||
    !Number.isInteger(result.remaining_after_sale) ||
    typeof result.movement_id !== "string" ||
    typeof result.replayed !== "boolean"
  ) {
    throw new Error("Unexpected sale response");
  }

  return result;
}

This helper assumes that the caller supplies an authenticated, request-scoped Supabase client.

For server-side Next.js applications, use the appropriate cookie-aware Supabase SSR setup.

Do not use a service-role client simply to bypass a permission error.

And don't trust browser-side validation alone. SQL validation and authorization remain essential.

Preserve the request ID during retries

Generate one unique request ID for each intended sale.

If a network request times out, you may not know whether the database committed it.

Retrying with a fresh ID can accidentally record another sale.

Instead, keep the original request ID for that same intended operation.

ts
const requestId = crypto.randomUUID();

Create that ID once, then preserve it through retries until the outcome is resolved.

A replayed response may report the balance immediately after the original sale, not the product's latest balance after other transactions. Fetch the current product record when you need the latest stock.

8. How to test inventory concurrency

This is the most important test in the entire tutorial.

Don't stop after successfully recording one sale.

A concurrency problem may only appear when multiple requests arrive at nearly the same time.

Test 1: Two simultaneous sales

Create a test product with one available unit.

Send two sale requests concurrently using different request IDs.

Expected behavior:

CheckExpected result
Starting stock1
Sale ASucceeds or loses race
Sale BSucceeds or loses race
Total successful salesExactly 1
Final stock0
New movement recordsExactly 1

Both requests must not successfully sell the last unit.

Test 2: Retry the same sale

Repeat the same product, quantity, and request ID.

The expected behavior is that the system returns the existing movement instead of subtracting stock again.

Test 3: Unauthorized access

Create two separate authenticated test users.

Attempt to read and sell another user's product.

Those operations should be denied.

Test 4: Invalid quantities

Try zero, negative quantities, null inputs, and values above the allowed limit.

Every invalid request should fail without changing inventory.

Test 5: Transaction rollback

In a controlled test environment, cause the movement insert to fail.

Verify that the stock balance remains unchanged.

Verification status: These are test cases and expected outcomes, not results observed during this article's preparation. Execute them using real authenticated database sessions before deploying the example.

Verification Note: The scenarios above describe expected outcomes, not independently executed database tests. Validate concurrency, RLS permissions, retries, and transaction rollback in a disposable Supabase environment before production use.

9. Display inventory in Next.js

A product listing is a good fit for a React Server Component.

For example, a server-rendered product page can retrieve products for the current authenticated user and display available balances.

The interactive sales form can use a Client Component or a form with a Next.js Server Action.

A typical flow looks like this:

text
User opens inventory page
         |
         v
Next.js loads authorized products
         |
         v
User enters sale quantity
         |
         v
Server validates request
         |
         v
Supabase RPC performs the sale
         |
         v
UI refreshes the stock display

Server Components can reduce the amount of JavaScript needed for some page content, but that doesn't automatically guarantee faster pages.

Measure performance with real tests rather than assuming every server-rendered page is fast.

10. Should you add Supabase Realtime?

Realtime can be useful when several employees keep an inventory dashboard open.

For example, you might want one screen to refresh when another user records a sale.

Supabase supports listening for PostgreSQL changes, but you must configure the relevant publication and permissions correctly.

Realtime also introduces additional concerns:

  • Subscription lifecycle and cleanup
  • Authentication and authorized event access
  • Reconnection handling
  • Multiple simultaneous users
  • Duplicate refreshes and unnecessary requests

For a first inventory prototype, I'd recommend getting the transactional sale workflow correct before adding realtime updates.

A stale screen can be refreshed.

An incorrect inventory balance is harder to recover from.

11. Common mistakes when building inventory software

Relying on frontend stock checks

A JavaScript check can improve the user experience, but it cannot guarantee inventory correctness under concurrency.

Put the final stock decision in the database.

Treating an RLS policy as complete business authorization

A policy that merely checks:

sql
with check (reason = 'sale')

does not prove that the user owns the product, that enough stock exists, or that the quantity is valid.

Business rules and access rules must work together.

Forgetting request retries

Network errors happen.

Without a stable request ID, retries can create duplicate stock movements.

Storing movements without thinking about performance

A movement ledger is useful for history and auditing, but large ledgers require sensible indexes and query design.

Measure real queries before introducing complicated caching.

Adding adjustments without updating the consistency rules

Sales, returns, purchases, damaged stock, and corrections all affect inventory.

Every new write path must preserve the relationship between the balance and its movement history.

Testing with only one user

Single-user testing cannot reveal many concurrency and authorization problems.

Use independent authenticated sessions and test competing operations deliberately.

12. Is this enough for a real inventory management application?

Not by itself.

A complete application may also need:

  • Organization membership and staff roles
  • Product SKUs and barcode support
  • Supplier and purchase-order records
  • Stock receipts, returns, and adjustments
  • Multiple warehouses or locations
  • Transaction history and reporting
  • Backups, monitoring, and audit controls

Those features introduce new security and data-integrity requirements.

Treat this guide as a foundation for understanding the critical stock-sale workflow.

PostgreSQL Concurrency and RLS Verification

The inventory workflow is designed to prevent overselling by handling stock checks and updates inside a PostgreSQL transaction.

Before using it in production, verify the following scenarios in a disposable Supabase database.

1. Normal Sale

Selling 2 units from an initial stock of 10 should leave 8 units available.

2. Concurrent Sales

When two users attempt to purchase the last available unit simultaneously, exactly one sale should succeed.

3. RLS Ownership

User B should not be able to access or modify inventory belonging to User A.

4. Duplicate Request Protection

Retrying the same request ID with identical inputs should not create another sale or reduce stock again.

5. Transaction Rollback

If inserting a stock movement fails, the preceding stock update should also be rolled back.

Verification Note: These scenarios describe expected outcomes, not independently executed test results. Validate concurrency, RLS permissions, retries, and transaction rollback in a disposable Supabase environment before production deployment.

Final thoughts

Building an inventory management system with Next.js and Supabase is a useful way to learn something that simple CRUD tutorials often miss: data integrity under competing requests.

A product table is straightforward. A sales form is straightforward.

Ensuring that two requests cannot sell the same last item is where database design starts to matter.

The practical takeaways are:

  • Record stock changes so you have an audit trail.
  • Keep critical balance changes and movement records in one transaction.
  • Enforce authorization in the database.
  • Protect retries with stable request identifiers.
  • Test concurrency rather than assuming atomicity.
  • Add reporting and realtime features after the stock workflow is reliable.

If you understand those principles, you'll have a much stronger starting point for designing inventory software.


Official documentation

Keep the conversation useful

Found a different result?

Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.

Send a correction or question

Share this article