All jobs

Add Role-Based Access Control to a NextAuth.js App

Yes. An agent adds an admin role to the Auth.js session, guards pages in middleware and API routes in their own handlers, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent starts with the one file that shapes the session. In an app like nextauthjs/next-auth-example that is auth.ts at the repository root: a single NextAuth call with 31 providers, session: { strategy: "jwt" }, basePath: "/auth", an UnstorageAdapter that uses a memory driver unless the app runs on Vercel, and three callbacks. authorized returns !!auth for /middleware-example and true for everything else, jwt copies a Keycloak access token and applies a client-side name update, and session exposes that token. middleware.ts re-exports auth as the middleware with a matcher that skips anything starting with api. app/api/protected/route.ts wraps its handler in auth(...) and answers 401 without a session. There is no user table to put a role column in, no lockfile, and package.json has dev, build and start and nothing else.

Where the role comes from decides most of the change. The Auth.js guide assigns it in a provider's profile() callback, which with 31 providers means 31 edits, so the agent uses the one place every sign-in passes through. It adds lib/roles.ts with a pure roleFor(email) that reads a comma-separated AUTH_ADMIN_EMAILS, trims and lowercases each entry, and returns "admin" or "user". The jwt callback sets token.role = roleFor(token.email) on every call, not only at sign-in, so taking an address out of the variable applies on the next request after a deploy instead of when the cookie runs out. The existing branches stay as they are: the trigger === "update" line that the client example's rename form depends on, and the Keycloak token. The session callback copies the role to session.user.role, and the declare module blocks at the bottom of auth.ts, which already add accessToken, gain role on the session's user and on JWT.

Enforcement goes in two places, because of that matcher. For pages, authorized gets a rule for /admin: no session returns false, which sends the visitor to sign in, and a session without the role is redirected to the home page, since bouncing a signed-in user to the sign-in screen tells them nothing. The new app/admin/page.tsx calls auth() and checks the role again itself, so the page does not depend on the middleware having run. For the API, the middleware never sees app/api/*, so app/api/admin/route.ts uses the same auth((req) => ...) wrapper as the protected route and answers 401 with no session and 403 with the wrong role. The agent leaves app/client-example/page.tsx alone: it deliberately strips the session down to name, email and image before handing it to SessionProvider, so the role never reaches the browser there.

The repository has no test runner, so the agent adds Vitest as a dev dependency with a test script and covers the parts that are plain functions: roleFor with mixed case, stray spaces, an unset variable and a missing email, and the path decision behind authorized, pulled into a function that takes a pathname and a session. It installs with pnpm, as the README and the Dockerfile do, runs tsc --noEmit and pnpm build, and adds AUTH_ADMIN_EMAILS to .env.local.example with a comment. The install writes a pnpm-lock.yaml and the build rewrites tsconfig.json and next-env.d.ts; the agent keeps all three out of the diff.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add role-based access control to this Next.js app, which uses Auth.js (next-auth v5) with JWT sessions. Read auth.ts, middleware.ts, app/api/protected/route.ts, app/client-example/page.tsx, components/session-data.tsx, package.json and .env.local.example first. Add lib/roles.ts with roleFor(email): it reads a comma-separated AUTH_ADMIN_EMAILS, compares case-insensitively, and returns \"admin\" or \"user\". In auth.ts set token.role in the jwt callback on every call (keep the existing update and Keycloak branches), expose it as session.user.role in the session callback, and extend the existing module augmentation for Session and JWT. Extend the authorized callback so /admin and anything under it needs the admin role: no session returns false, a session without the role redirects to /. Add app/admin/page.tsx that checks the role again with auth(), and app/api/admin/route.ts that answers 401 without a session and 403 without the role, because the middleware matcher skips /api. Do not pass the role through SessionProvider in the client example. Add Vitest with a test script and test roleFor and the path decision as pure functions. Install with pnpm, run tsc --noEmit, the tests and pnpm build, document AUTH_ADMIN_EMAILS in .env.local.example, and open a pull request that says what was tested and what was only compiled.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

A pull request with lib/roles.ts, the three changed callbacks and the widened type declarations in auth.ts, the admin page and the admin route, the Vitest setup with its tests, and one new line in .env.local.example. Its description lists each path and what answers there for three visitors: signed out, signed in, and signed in as an admin. It also states the versions of next and next-auth the install resolved, because package.json asks for latest and beta and there is no lockfile to pin them, and which paths were exercised by tests and which were only compiled.

A reviewer starts with trust in the email. An allow-list keyed on an address is only as good as the provider that asserted it, and this app accepts 31 of them, so the question is whether an admin address could be claimed through a provider that does not verify email. The description raises this and names the narrower option, checking account.provider at sign-in and granting the role only through providers you name. The reviewer also confirms that every admin API route checks the role in its handler, since nothing in the middleware will do it for them, and that the token carries a role name and nothing more sensitive.

Run it on every Linear issue labelled access-control

Role work arrives one protected area at a time: the billing page this week, the export endpoint the next. In the console, add an automation on the Project that holds the app, with a linear trigger on linear.issue.labeled and the label access-control, and a saved prompt that tells the agent to guard whatever the issue names in the pattern already in the repository: a rule in authorized for pages, a check in the handler for API routes, a test for each. The issue is added after the prompt when a person in your Rush org applies the label, and each run opens its own pull request. The automation's runner needs a Linear connection, made in the console under Settings → Connections.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Access control fails at the edges: the route the middleware does not match, the page that trusts the middleware, the address typed with a capital letter. The agent works in a sandbox with the whole app installed, so those edges are compiled and tested, not reasoned about, and the run keeps every command with its output. When the pull request says the admin route answers 403 for a signed-in user, the test that shows it and the pnpm build that included it are in the run's record.

No one's Google or GitHub client secret is in the sandbox, so the run cannot click through a real sign-in, and the result says so plainly. What comes back is a branch a person can check out, add their own .env.local to, and try with two accounts in a few minutes, with the logic already covered.

Frequently asked questions

If I remove someone from AUTH_ADMIN_EMAILS, when do they lose access?

On their next request after the new value is deployed. The role is recomputed from the token's email every time the jwt callback runs, so it is not frozen into the cookie at sign-in. Had it been set only at sign-in, they would keep it until the session expired or they signed out.

Does the middleware protect my API routes too?

Not in this setup. The matcher in middleware.ts excludes paths that start with api, so those requests never reach authorized. Each admin route checks the session and the role in its own handler, and the pull request includes one as the pattern.

Can roles come from a database instead of an environment variable?

Yes, once the app has a persistent adapter with a user table. The role then becomes a column and roleFor reads it; the callbacks, the type declarations and the checks stay the same. The example's adapter keeps users in memory outside Vercel, so a column there would be lost on restart.

More NextAuth.js jobs

The same job on other stacks

More jobs like this: Turn a Linear label into a PR

Keep reading