Authorization

Nuxt Server Utils provides a simple way to protect your API with authorization. It provides a instance of Authorizer class that can be used to protect your API endpoints.

Allowing access to authenticated users

The Authorizer.allows method is used to allow access to authenticated users. It accepts the event object and a callback function that returns a boolean value. If the callback function returns true, the request is allowed to proceed. If the callback function returns false, the request is rejected with a 403 Forbidden error.

server/api/users.get.ts
import { Authorizer } from "#nuxt-server-utils";

export default defineEventHandler(async (event) => {

  const authenticatedUser = await event.context.auth.user;
  Authorizer.allows(event, () => authenticatedUser.isAdmin);

  // ...
});

The Authorizer.allows method accepts the following arguments:

  • event - The event object.
  • callback - A callback function that returns a boolean value.
  • error - An optional error object or message to use when rejecting the request.