Designing Authentication and Authorization for Business Apps with Next.js and Supabase

Introduction
Authentication and permission management for business apps built with Next.js and Supabase is a design in which Supabase Auth determines who can log in, and Row Level Security determines who can read and write which rows. You can design this by working through four stages in order: selecting an authentication method, designing role information, implementing Row Level Security policies, and handling sessions on the Next.js side. This article is aimed at engineers developing business apps in small teams, and uses an expense reimbursement app as an example to show, with SQL and code examples, everything from identifying roles and operations, implementing the user_roles table and custom claims, policies using auth.uid() and auth.jwt(), to session verification in Server Components and Middleware.
Conclusion: Before implementation, settle on the types of users (employees only, or including people outside the company) and which tables each role operates on. This is because changing the authentication method or the scope of Row Level Security later on broadens the impact.
How to Identify the Roles and Permissions Needed for a Business App
Identifying roles is less likely to leave gaps if you first align the list of features with the granularity of operations, and then assign roles in that order. Enumerate the screens and features of the business, associate each one with which of SELECT, INSERT, UPDATE, or DELETE occurs on a per-table basis, and name the group of people who perform that operation as a role.
If you define roles directly as department names or job titles, you'll end up rewriting policies every time the organization changes. Organizational names such as General Affairs Department or Sales Department should be treated not as roles themselves, but as attributes attached to a role (a department scope); doing so decouples the structure of the user_roles table from organizational changes.
Identifying these for an expense reimbursement app looks like this:
| Feature | Table | Operation | Target Role |
|---|---|---|---|
| Create own request | expenses | INSERT | General employee |
| View own request | expenses | SELECT | General employee |
| Approve subordinate's request | expenses | UPDATE | Approver |
| View all requests | expenses | SELECT | Accounting approver |
| Cancel a request | expenses | DELETE | Requester themselves / Accounting approver |
The "Target Role" column in this table is used directly as the value in the user_roles table and as the condition in policies in later stages. Rows where two target roles appear side by side, such as "Cancel a request," can be identified at this stage as places where the condition should be joined with "or" rather than "and."
Types of Authentication Methods Available in Supabase Auth
Supabase Auth lets you choose from email and password, magic links, email OTP, SMS OTP, OAuth (such as Google or GitHub), and SSO via SAML. Regardless of which method is used to log in, the resulting JWT has the same shape, the user is registered in the same auth.users table, and the same user_roles is referenced via the UUID returned by auth.uid().
The strength of permissions is determined not by the authentication method but by user_roles and policies. There's no need to separate role determination by method; the only things to consider when choosing a method are the types of users and login frequency. The specific choice is covered in Step 1 below.
Step 1: Choose an Authentication Method with Supabase Auth

Conclusion: If only employees will use the app, choose OAuth or SSO via SAML; if external users are included, choose email/password or email OTP. The strength of permissions is determined not by the method, but by the roles and policies from Step 2 onward.
Choosing Between Email/Password Authentication and OAuth Integration
Whether users include external business partners or temporary contacts, or whether operations can rely solely on employees' internal accounts, determines which approach you should take.
Email/password authentication is fully self-contained within Supabase and does not depend on an external identity provider. In exchange, your organization bears the operational burden of issuing, reissuing, and revoking passwords. If you register a partner contact who logs in only a few times a month, you need to set up a password reset flow from the start—otherwise, the less frequently a user logs in, the more support inquiries you will receive.
With OAuth integration, employees can log in using the Google, GitHub, or other accounts they already use internally, eliminating the burden of password management. In organizations where accounts are centrally managed through an HR system, disabling an internal account also disables any new logins. However, an already-issued Supabase session is not automatically terminated when the account is disabled on the OAuth side, so when an employee leaves, invalidating the session and deleting the corresponding row in user_roles must be included in the procedure.
Choose email/password authentication if external users are involved, and OAuth if operations can be handled with employee accounts alone. Even if you use different methods for different user groups, the role-determination logic can remain shared.
When to Use Magic Link and OTP Authentication
Magic links and email OTP are methods to choose when the effort of issuing and resetting passwords doesn't match how often users actually log in. For partner contacts who log in only a few times a month, or for contractors involved only for a short period, you can skip issuing passwords and instead send a login link or code by email. With Supabase Auth, you can send one simply by calling signInWithOtp.
Which one to choose depends on the user's environment. Magic links require just a click, but in environments where email security products or preview features open the link first, the link may get consumed and cause the login to fail. If you cannot control the email environment of your business partners, email OTP—where the user manually enters a number—is the less failure-prone choice.
SMS OTP sent to a phone number suits on-site workers who don't have a business email address. Regardless of which method is assigned, Row Level Security policies are determined solely by how roles are held, so there is no need to write separate conditional expressions for each method.
Step 2: Design User Role Information in the Database

Conclusion: Store roles in the user_roles table with one role per row, and attach them to the JWT via the Custom Access Token Hook. This is because the JWT issued immediately after login contains only things like the user ID, and no role information is included anywhere.
How to Link the Role Table with User IDs
The user_roles table should hold the UUID returned by auth.uid() as a foreign key, with the role column linking to the role. Since one row represents "a given user has one role," a user such as a department manager—who both submits their own expense claims and approves their subordinates' claims—should be registered with separate rows for each role under the same user_id.
1create table public.user_roles (
2user_id uuid references auth.users (id) on delete cascade,
3role text not null,
4primary key (user_id, role)
5);The role column can be defined as either text type or enum type. Using an enum type prevents inconsistent notation, such as a mix of "approver" and "Approver." Either way, if you use the same names from the role-identification table as the actual values, you'll save the trouble of mapping names when writing policies.
When a transfer happens, you can remove only the "approver" row from user_roles to revoke approval authority while keeping the account intact. If you specify cascading delete on the foreign key, deleting a user from auth.users will also remove the corresponding rows in user_roles, preventing a departed employee's roles from lingering. The primary key is set as the combination (user_id, role) in order to prevent duplicate registration of the same role while still allowing multiple roles to coexist.
How to Include Roles in JWT Custom Claims
By implementing the Custom Access Token Hook as a Postgres function and enabling it under Auth Hooks in the Supabase dashboard, you can reference user_roles at token issuance time and embed the role into the JWT. Because the role is included in the token, Row Level Security policies and Next.js Middleware can determine the role without querying the database.
1create or replace function public.custom_access_token_hook(event jsonb)
2returns jsonb
3language plpgsql
4stable
5as $$
6declare
7claims jsonb;
8user_role text;
9begin
10select role into user_role
11from public.user_roles
12where user_id = (event->>'user_id')::uuid
13order by case role when 'approver' then 0 else 1 end
14limit 1;
15
16claims := event->'claims';
17claims := jsonb_set(claims, '{user_role}',
18coalesce(to_jsonb(user_role), 'null'::jsonb));
19return jsonb_set(event, '{claims}', claims);
20end;
21$$;The order by clause prioritizes the approver role over regular employee, so that a user holding a dual role is given the stronger role. For a user with no roles at all, to_jsonb returns null, which would make the entire result of jsonb_set null and prevent the token from being issued—so coalesce is used to replace it with a JSON null instead. If you want policies to check for both roles, make the claim an array.
This function is executed by supabase_auth_admin, Supabase Auth's internal role. Grant execute privileges on the function only to supabase_auth_admin, revoke them from anon and authenticated, and also grant supabase_auth_admin read access to user_roles (the steps are provided in the official RBAC guide).
The added claim can be referenced via auth.jwt() ->> 'user_role'. Note, however, that role changes are not reflected in already-issued access tokens—the old claim remains until the token is refreshed. When revoking an approver's permissions, be sure to also invalidate the session.
Step 3: Design Row Level Security Policies

Conclusion: Enable Row Level Security for each table, and write SELECT, INSERT, UPDATE, and DELETE as separate policies. Once enabled on a table, it will not return any rows if there is not a single policy defined.
Separating SELECT, INSERT, UPDATE, and DELETE Policies for Each Table
If you cram conditions for multiple operations into a single policy, you lose track of which operation is permitted under which condition. Since create policy lets you specify the operation via the for clause, you should create a separate policy for each of SELECT, INSERT, UPDATE, and DELETE.
For the expenses table of an expense reporting app, you would define separate policies: one for regular employees to create and view their own expense claims, and another for approvers to update claims. If approval should be limited to the claims of one's subordinates, you add a condition on the department column.
1create policy "select_own_expenses"
2on public.expenses for select
3using (auth.uid() = user_id);
4
5create policy "insert_own_expenses"
6on public.expenses for insert
7with check (auth.uid() = user_id);
8
9create policy "update_as_approver"
10on public.expenses for update
11using (auth.jwt() ->> 'user_role' = 'approver');SELECT and DELETE use the using clause to restrict existing rows, while INSERT uses the check clause to restrict the values being inserted. UPDATE can include both, allowing separate conditions for the row before the update and the values after the update. By separating policies by operation, you can later extend DELETE alone to a different role without touching the conditions for other operations, and each row in your inventory table corresponds one-to-one with a policy.
When you create multiple policies for the same table and the same operation, Postgres combines them with OR. By making "SELECT by the owner" and "SELECT by an accounting approver" separate policies, a row can be read if either condition is satisfied.
How to Write Policy Conditions Using auth.uid() and auth.jwt()
auth.uid() is a function that returns the UUID of the currently logged-in user, and it's used for conditions determined solely by whether someone is the owner. auth.jwt() returns the entire decoded JWT, so it's used to extract custom claims—such as a user_role set via a Custom Access Token Hook. The two can be combined with or within the same policy.
1create policy "select_own_or_admin"
2on public.expenses for select
3using (
4auth.uid() = user_id
5or auth.jwt() ->> 'user_role' = 'accounting_approver'
6);This is written so that the owner's own row is matched via auth.uid(), while an accounting approver is allowed to SELECT all rows based on the claim value. Since the ->> operator returns text, you should match the comparison value as a string as well. If your design stores roles as an array in the claim, the approach changes to extracting the value with -> and checking for the presence of an element with the ? operator, so you should decide in advance whether it will be a single string or an array.
When mixing in negative conditions, make the scope explicit with parentheses so that the owner's condition and the role's condition don't cancel each other out. If the same role check is used across multiple tables, extracting the comparison logic into a Postgres function means that if the claim name changes, you only need to fix it in one place.
Step 4: Handling Sessions and Permissions on the Next.js Side

Conclusion: Authorization decisions should be made using only user information verified on the server side, and client-side role checks should be limited to switching what's displayed. Even though Row Level Security is a defensive line on the database side, mishandling things on the Next.js side can leak information that shouldn't be shown on screen.
Checking Sessions in Server Components and Middleware
createServerClient can read cookies from both Server Components and Middleware, but their roles differ depending on whether they can write. Server Components cannot rewrite cookies during rendering, so even when a token is refreshed, the new cookie cannot be reflected in the response. Middleware takes on this writing responsibility, verifying the session on every request and writing the refreshed token back into both the request and response cookies.
1// middleware.ts (from Next.js 16 onward, the file is named proxy.ts and the function is named proxy)
2import { createServerClient } from '@supabase/ssr'
3import { NextResponse, type NextRequest } from 'next/server'
4
5export async function middleware(request: NextRequest) {
6let response = NextResponse.next({ request })
7const supabase = createServerClient(
8process.env.NEXT_PUBLIC_SUPABASE_URL!,
9process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
10{
11cookies: {
12getAll: () => request.cookies.getAll(),
13setAll: (cookies) => {
14cookies.forEach(({ name, value }) => request.cookies.set(name, value))
15response = NextResponse.next({ request })
16cookies.forEach(({ name, value, options }) =>
17response.cookies.set(name, value, options))
18},
19},
20}
21)
22await supabase.auth.getUser()
23return response
24}In Server Components and Route Handlers as well, you should call auth.getUser() from the same createServerClient to make determinations. getSession() returns the contents of the cookie without verifying its signature, so it would end up trusting a tampered cookie as-is. For authorization decisions, use getUser(), which returns user information verified by the Auth server.
The matcher should comprehensively include paths whose display changes based on permissions, such as approval screens or the full listing view for accounting approvers. On routes that don't pass through Middleware, the token won't be refreshed, which can cause the session to be cut off midway or cause decisions to be made using stale claims. The only paths that should be excluded from the matcher are static pages that anyone can view before logging in.
How to Use Permissions for UI Display Control on the Client Side
If you're only switching the display of approval buttons or admin-department menus, it's fine to determine the role on the client side. However, this is merely a matter of appearance control—whether data operations are permitted is ultimately decided by Row Level Security. The role should be retrieved in a Server Component and passed to the client component via Props.
1// app/expenses/page.tsx (Server Component)
2import { decodeJwt } from 'jose'
3
4export default async function Page() {
5const supabase = await createClient() // a function wrapping createServerClient
6// Verify the user with getUser(), then read the token from the same session
7const { data: { user } } = await supabase.auth.getUser()
8const { data: { session } } = await supabase.auth.getSession()
9const role = user && session
10? (decodeJwt(session.access_token).user_role as string | null)
11: null
12return <ExpenseList role={role} />
13}Since the return value of getUser() does not include the session, verification should be done with getUser(), while claims should be read from the access token returned by getSession(). The client component should not decode the token itself, but should simply switch the display based on the received role.
The point where misjudgment easily occurs is the initial render, before the role has been determined. If you write the branch that skips rendering the approval button while role is null first, you can prevent a situation where the button briefly appears to a regular employee. Immediately after a role change, the client's role remains outdated, but since the update operation is rejected by the server-side policy, this display discrepancy does not lead to a data leak.
Common Mistakes and How to Avoid Them

Conclusion: Most incidents come down to two causes: forgetting to enable Row Level Security, and exposure of the service_role key. Either one allows the policy evaluation itself to be bypassed entirely, even when the design is otherwise correct, so these should be checked before applying to production.
Forgetting to Enable Row Level Security, Causing All Data to Be Retrieved
A table created with SQL has Row Level Security disabled by default, and depending on the Data API's permission settings, unauthenticated requests using the anon key, as well as logged-in users (the authenticated role), may be able to perform SELECT or INSERT on the entire table without restriction. Even if you've built out user_roles and a Custom Access Token Hook, if you forget to enable it on the table that actually matters, the policy is never evaluated at all, and all rows can be read and written regardless of role.
1alter table public.expenses enable row level security;If you forget to enable it on expenses, an unauthenticated request can retrieve, in a single query, all the expense reports that only accounting approvers should be able to see. Once enabled, the same request will return 0 rows.
The way to avoid this is to write create table and enable row level security in the same migration file that creates the table, so that there is never a window of time when an unprotected table exists. Before deploying, check the enabled/disabled status of every table in a single list in the admin dashboard, and test SELECT, INSERT, UPDATE, and DELETE with test accounts for regular employees, approvers, and accounting approvers before applying changes to production.
Exposing the Service Role Key on the Client Side
Because the service_role key bypasses all Row Level Security policies, if it leaks into the client side, role determination and user_roles become meaningless. A typical way this happens is defining this key under an environment variable name that starts with NEXT_PUBLIC_. Next.js embeds environment variables with this prefix into the browser-facing bundle at build time, making the value readable from developer tools.
# Wrong: exposed to the client NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY=... # Correct: loaded server-side only SUPABASE_SERVICE_ROLE_KEY=...
With an exposed key, even a full-table SELECT or DELETE that should be rejected without an accounting approver's claims can be executed from the browser. Since the key itself bypasses evaluation even when the policy conditions are correct, revisiting the policies will not prevent this.
Before deploying, grep under .next/static to check whether the key's value is included in the bundle. If it's found, simply renaming the variable is not enough—you must revoke the key, switch to a new one, and also check your commit history and logs. Batch processes that intentionally bypass RLS should be run only server-side, such as in Route Handlers or Edge Functions.
Frequently Asked Questions

This covers three topics: the priority order of Row Level Security, retrofitting it into an existing application, and permission design in a multi-tenant configuration.
Q1: Which Should Take Priority, Row Level Security or API-Side Permission Checks?
Row Level Security serves as the final line of defense for data access, with API-side checks positioned as a supplement to business logic. Since operations that fail to satisfy a policy are rejected regardless of the route they come through, even if there are gaps in Route Handler or Server Components processing, unauthorized updates to the expenses table are prevented. Business rules and rate limits—such as preventing re-editing of already-approved requests or warning when an amount exceeds a limit—are handled on the API side, with the two layers functioning together as separate lines of defense.
Q2: Can Row Level Security Be Introduced to an Existing Business App Later?
This can be introduced. The steps are as follows:
- Enable the target table using ALTER TABLE
- Define policies for each anticipated SELECT, INSERT, UPDATE, and DELETE operation
- Verify behavior for each role in a staging environment
- Apply the changes to the production migration
In environments where production data persists, operations lacking a defined policy are immediately rejected, so apply changes only after verification is complete.
Q3: How Should Permission Design Change for Multi-Tenant Business Apps?
How you divide tenants determines how you approach permission design.
In the approach where a tenant column is added to the main tables, the role condition and tenant condition are joined with "and." You add a tenant_id column to expenses and user_roles, use the Custom Access Token Hook to insert a tenant_id claim into the JWT, and add tenant_id = (auth.jwt() ->> 'tenant_id')::uuid to each policy with "and." Since ->> returns text, this cast is necessary if the tenant_id column is of type uuid (it's not needed if the column is of type text). If this condition is omitted, approvers would be able to update requests belonging to other companies.
In the approach where schemas are separated by tenant, the focus shifts away from policy conditions and centers instead on the operational design of schema creation and migration application, which occur each time a tenant is added.
Conclusion

Authentication and permission management for business applications is built around four stages: selecting an authentication method, designing role information, implementing Row Level Security policies, and handling sessions on the Next.js side. Since the shape of the JWT doesn't change regardless of the authentication method, there's no need to separate role determination by method. Row Level Security is enabled per table, with policies for each operation written using auth.uid() and auth.jwt(). On the Next.js side, authorization is determined solely using user information verified on the server, while role determination on the client is limited to switching what is displayed. Forgetting to enable it and exposing the service_role key can be prevented by establishing conventions for how migrations are written and how keys are named. Start by listing out the features of your own business application in a table and identifying which roles perform which operations.
References
- www.ipa.go.jp/archive/files/000004509.pdfAccessed December 1, 2026
- www.ncsc.gov.uk/pdfs/guidance/authentication-methods-choosing-the-right-type.pdfAccessed December 1, 2026
- www.ipa.go.jp/archive/publish/qv6pgp0000000wrt-att/000079352.pdfAccessed December 1, 2026
- supabase.com/docs/guides/database/postgres/row-level-securityAccessed December 3, 2026
- supabase.com/docs/guides/authAccessed December 3, 2026
- supabase.com/docs/guides/auth/jwt-fieldsAccessed December 3, 2026
- supabase.com/docs/guides/api/custom-claims-and-role-based-access-control-rbacAccessed December 3, 2026
- supabase.com/docs/guides/auth/auth-email-passwordlessAccessed December 3, 2026
- supabase.com/docs/reference/javascript/auth-signinwithotpAccessed December 3, 2026
- supabase.com/docs/guides/auth/enterprise-sso/auth-sso-samlAccessed December 3, 2026
- supabase.com/docs/guides/auth/managing-user-dataAccessed December 3, 2026
- supabase.com/docs/guides/api/api-keysAccessed December 3, 2026
- www.postgresql.org/docs/current/ddl-rowsecurity.htmlAccessed December 3, 2026
- supabase.com/docs/guides/auth/auth-email-passwordlessAccessed December 3, 2026
- supabase.com/docs/guides/auth/auth-hooksAccessed December 3, 2026
- supabase.com/docs/guides/auth/auth-hooks/custom-access-token-hookAccessed December 3, 2026
- supabase.com/docs/guides/auth/server-side/creating-a-clientAccessed December 3, 2026
- supabase.com/docs/guides/auth/jwtsAccessed December 3, 2026
- supabase.com/docs/guides/auth/passwordsAccessed December 3, 2026
- supabase.com/docs/guides/auth/custom-oauth-providersAccessed December 3, 2026
- www.postgresql.org/docs/17/ddl-rowsecurity.htmlAccessed December 3, 2026
- supabase.com/docs/guides/getting-started/tutorials/with-nextjsAccessed December 3, 2026
- Next.js DocsAccessed December 3, 2026
Author & Supervisor
Yusuke Ishihara
Started programming at age 13 with MSX. After graduating from Musashi University, worked on large-scale system development including airline core systems and Japan's first Windows server hosting/VPS infrastructure. Co-founded Site Engine Inc. in 2008. Founded Unimon Inc. in 2010 and Enison Inc. in 2025, leading development of business systems, NLP, and platform solutions. Currently focuses on product development and AI/DX initiatives leveraging generative AI and large language models (LLMs).


