Sign in

Function: authMiddleware

Call Signature

authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware

Creates a Next.js authentication middleware that protects routes.

By default, all routes matched by config.matcher are protected unless configured otherwise.

Parameters

ParameterTypeDescription
options?MonoCloudMiddlewareOptionsOptional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).

Returns

NextMiddleware

Returns a Next.js middleware result, such as a NextResponse, redirect, or undefined to continue processing.

Examples

src/proxy.ts
import { authMiddleware } from "@monocloud/auth-nextjs";

export default authMiddleware();

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};

Call Signature

authMiddleware(request: NextRequest, event: NextFetchEvent): NextMiddlewareResult | Promise<NextMiddlewareResult>

Executes the authentication middleware manually.

Intended for advanced scenarios where the middleware is composed within custom logic.

Parameters

ParameterTypeDescription
requestNextRequestIncoming Next.js middleware request used to resolve authentication state.
eventNextFetchEventNext.js middleware event providing lifecycle hooks such as waitUntil.

Returns

NextMiddlewareResult | Promise<NextMiddlewareResult>

Returns a Next.js middleware result (NextResponse, redirect, or undefined to continue processing).

Example

src/proxy.ts
import { authMiddleware } from "@monocloud/auth-nextjs";
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";

export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {
  if (req.nextUrl.pathname.startsWith("/api/protected")) {
    return authMiddleware(req, evt);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};
© 2024 MonoCloud. All rights reserved.