VENNStart
Guide

Permissions and paid-plan checks in the Next.js App Router

Notes from a B2B SaaS dashboard on one permission module, checks split between Next.js and the API, and what to update when a role or plan changes.

Lê Anh Tuấn4 min read

The menu hides "Manage users" from members, but pasting its URL still opens the page. Hiding a link only changes what people see, and access has to be checked where requests arrive. The project was a B2B SaaS dashboard with paid plans on the App Router, with users, roles and billing stored by a separate API. The refresh token post covers renewing the session.

The API enforces, Next.js handles UX

Hiding a button, redirecting in proxy or rendering a "no access" page only shapes the UI, and none of it stops a request sent straight to the API. The API checks role and plan on every request as if the frontend didn't exist. The Next.js authentication guide also calls Proxy checks "optimistic".

One module maps roles to permissions

This project's settings menu filters items with user?.role === 'admin'. If each screen compares roles like that, adding a "billing manager" role means hunting down every comparison. I'd move to one module that maps roles to permissions, with every other file calling can() with a permission:

// lib/permissions.ts: imported by server and client code
export type Role = 'owner' | 'admin' | 'member' | 'viewer'

export type Permission =
  | 'billing:manage'
  | 'members:invite'
  | 'members:remove'
  | 'reports:export'
  | 'projects:edit'

const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> = {
  owner: ['billing:manage', 'members:invite', 'members:remove', 'reports:export', 'projects:edit'],
  admin: ['members:invite', 'members:remove', 'reports:export', 'projects:edit'],
  member: ['projects:edit'],
  viewer: [],
}

export type SessionUser = { id: string; role: Role }

export function can(user: SessionUser | null | undefined, permission: Permission): boolean {
  if (!user) return false
  return ROLE_PERMISSIONS[user.role]?.includes(permission) ?? false
}

can() returns false for a missing user or an unknown role, on purpose, so a new API role needs a mapping before the UI lets anyone click. The module has no server-only or browser-only imports, so every layer can use it. If your API returns permissions directly, drop the map.

Proxy only reads cookies

Next.js 16 calls this file proxy.ts, and on the project's 15 it's middleware.ts. Proxy runs on every matched route, prefetches included, so read the cookie and skip database queries and API calls. Anything not listed as public is private, so new pages are protected by default:

// proxy.ts (Next.js 16). On Next.js 15: middleware.ts, export function middleware
import { NextResponse, type NextRequest } from 'next/server'

const PUBLIC = ['/login', '/signup', '/forgot-password']
const ALLOWED_WITHOUT_PLAN = ['/settings/billing', '/logout']

const matches = (path: string, list: string[]) =>
  list.some((p) => path === p || path.startsWith(`${p}/`))
export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl
  const hasSession = request.cookies.has('session')
  const planHint = request.cookies.get('plan-status')?.value // a hint, not proof

  if (matches(pathname, PUBLIC)) {
    return hasSession ? NextResponse.redirect(new URL('/', request.url)) : NextResponse.next()
  }
  if (!hasSession) {
    const login = new URL('/login', request.url)
    login.searchParams.set('next', pathname) // only accept relative paths on the way back
    return NextResponse.redirect(login)
  }
  if (planHint === 'inactive' && !matches(pathname, ALLOWED_WITHOUT_PLAN)) {
    return NextResponse.redirect(new URL('/settings/billing', request.url))
  }
  return NextResponse.next()
}
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|sw.js|manifest.webmanifest|\\.well-known/).*)'],
}

Public files got caught too. Login redirects hit an embedded HTML file, the iOS app-association file, the web manifest and the service worker. My first fix added apple-app-site-association to the negative lookahead, which is anchored at the path start and missed .well-known/.... Test the matcher with real file paths while logged out.

The live version also had proxy call the API's access check on every request from a subscribed user. It worked, but each navigation and prefetch waited on an extra call (I never measured how long), so I'd move it to the page.

The real check runs in the page

In the version I'd write, one helper reads the user and plan from the API:

// lib/dal.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { can, type Permission, type SessionUser } from './permissions'
import { accessFor, TIER_RANK, type PlanStatus, type Tier } from './entitlements'
export type Me = SessionUser & { plan: { tier: Tier; status: PlanStatus } }

export const getMe = cache(async (): Promise<Me | null> => {
  const token = (await cookies()).get('session')?.value
  if (!token) return null
  const res = await fetch(`${process.env.API_URL}/me`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  })
  return res.ok ? res.json() : null
})
export async function requirePermission(permission: Permission) {
  const me = await getMe()
  if (!me) redirect('/login')
  if (!can(me, permission)) redirect('/no-access')
  return me
}
export async function requirePlan(min: Tier) {
  const me = await getMe()
  if (!me) redirect('/login')
  if (accessFor(me.plan.status) === 'blocked' || TIER_RANK[me.plan.tier] < TIER_RANK[min]) redirect('/settings/billing')
  return me
}

A page starts with const me = await requirePermission('members:invite'). React's cache() makes all getMe() calls in a request share one fetch. no-store plus reading cookies() keeps per-user responses out of shared caches. Don't wrap this in 'use cache', because a cached scope can't read cookies().

A layout check alone isn't enough, since layouts don't re-render on client navigation and nested segments and Server Actions are separate entry points. Route Handlers and Server Actions use the same getMe() and can() but return 401 or 403, like public endpoints. forbidden() is still experimental behind experimental.authInterrupts as of 16.2, so I redirect.

The client would reuse can() through a <Can> component, with the root layout passing down only { id, role }. The current dashboard fetches the user into a client store after mount, so admin items can appear a beat late and the menu jumps. Rendering the user on the server avoids that.

Plans are separate from roles

A role is what a person may do, and a plan is what the team paid for. Because they change for different reasons, I'd give each its own module and map each plan status to an explicit decision:

// lib/entitlements.ts
export type PlanStatus = 'trialing' | 'active' | 'past_due' | 'canceled' | 'inactive'
export type Tier = 'free' | 'pro' | 'team'
export const TIER_RANK: Record<Tier, number> = { free: 0, pro: 1, team: 2 }

export function accessFor(status: PlanStatus): 'full' | 'grace' | 'blocked' {
  switch (status) {
    case 'active':
    case 'trialing':
      return 'full'
    case 'past_due':
      return 'grace' // let them in, ask for a new card
    default:
      return 'blocked'
  }
}

const FEATURES = {
  'reports:export': ['pro', 'team'],
  'members:invite': ['team'],
} as const satisfies Record<string, readonly Tier[]>

export const hasFeature = (tier: Tier, feature: keyof typeof FEATURES) =>
  (FEATURES[feature] as readonly Tier[]).includes(tier)

requirePlan('pro') uses accessFor() plus the tier rank to block whole pages, and hasFeature() blocks single actions like export.

Active and past-due got in, past-due with a modal linking to the billing portal. Everyone else went to login with a reason, even when the check itself failed. Failing closed protects revenue, but a billing outage takes the whole app down.

Both bugs I remember were in error paths. The first plan check in middleware used the shared API client, which read the token from document.cookie. Middleware runs on the server, where there's no document, so paying users were treated as unsubscribed. I switched to plain fetch with the token in a header.

In the second, the access-check endpoint returns 401 as a normal answer, while the client interceptor logs out on any 401. My first fix excluded the endpoint by its full /api/v1/... URL, but axios stores the path relative to baseURL, so it never matched. The next fix used includes('/subscriptions/check-access').

The static export for a native shell has no server, so plan checks run on the client and the API is the only gate.

When roles and plans change mid-session

When an admin demotes someone or a card gets declined, every cached copy is wrong at once. The plan-status cookie is only a hint for proxy. Users can edit it. Rewrite it when you learn the real state, and delete it with the session cookie on logout so a shared machine's next user doesn't inherit it.

A role inside a JWT is stale until the token refreshes, so either read it from the API each request like getMe() or force a refresh after a role change. For in-app changes, invalidate the related queries and call router.refresh(), which doesn't clear server-side caches.

For changes in an external billing portal, its return URL points at a Route Handler that reads the new state and rewrites the hint cookie:

// app/settings/billing/return/route.ts: the billing portal's return URL
import { NextResponse, type NextRequest } from 'next/server'
import { getMe } from '@/lib/dal'
import { accessFor } from '@/lib/entitlements'

export async function GET(request: NextRequest) {
  const me = await getMe() // read from the API, not from a stale claim
  if (!me) return NextResponse.redirect(new URL('/login', request.url))

  const response = NextResponse.redirect(new URL('/settings/billing', request.url))
  response.cookies.set('plan-status', accessFor(me.plan.status) === 'blocked' ? 'inactive' : 'ok', {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    path: '/',
  })
  return response
}

The return is a full page load, so proxy, layout and page all run again, and payment-provider webhooks update the API's copy.

When testing, type URLs and fire API requests before looking at the menu. A user still loading, a role that just changed and a failing billing service get missed, since a logged-in admin never hits them.

  • Next.js
  • RBAC
  • Authorization
  • App Router
  • SaaS
  • Security

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.