API Guards

unaunri API Guards are similar to Page Guards, except they belong to the server and will protect our API endpoints.

As an example, let's take MakerKit's implementation for handling user invites. We want to check that:

  • the user is authenticated
  • the endpoint method being called is correct
import { withAuthedUser } from '~/core/middleware/with-authed-user';

export default function inviteHandler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const handler = withMiddleware(

  return withExceptionFilter(req, res)(handler);

As you can see above, we're using various guards: withMethodsGuard and withAuthedUser.

These two guards will make sure that the request will get rejected if the user isn't authenticated or if the user submitted a request using a disallowed HTTP method.

You can also simplify the above if you only want to check if the user is signed-in:

export default function myAPIHandler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await withAuthedUser(req, res);

  // do something with res