Authorization

It uses a JWT (fun fact, it's pronounced "jot") token to authorize users. You can import auth() to wrap the protected API routes. Here's the example:

ts

import { auth, ReqWithUser } from '@/app/api/_middlewares/authorization' export const GET = auth(async (req: ReqWithUser) => { // get the user data from `req.user` })

ReqWithUser is an extended type of NextRequest that includes the user data. You can use it to get the user's name, email, and other user data.

āœ… It supports getting the JWT token from the cookie or the Authorization header.

Role-Based Access Control (RBAC)

NextReady also supports role-based access control (RBAC). You can create a role and assign it to the user in the admin panel (/~admin). Each user can have 1 role and multiple permissions.

  • withRoles

    Checking if the user has one of the required roles. Eg. withRoles(['user', 'admin']) it will check if the user has a user OR admin role.

    ts

    import { auth, ReqWithUser } from '@/app/api/_middlewares/authorization' import { withRoles } from '@/app/api/_middlewares/rbac' export const GET = auth( withRoles( ['user', 'admin'], async (req: ReqWithUser) => { // your code here } ) )
  • withPermissions

    Checking if the user has the required permissions. Eg. withPermissions(['user:read', 'user:write']) it will check if the user has both user:read AND user:write permissions.

    ts

    import { auth, ReqWithUser } from '@/app/api/_middlewares/authorization' import { withPermissions } from '@/app/api/_middlewares/rbac' export const GET = auth( withPermissions( ['user:read', 'user:write'], async (req: ReqWithUser) => { // your code here } ) )