Sign in

Function: isAuthenticated

Call Signature

isAuthenticated(): Promise<boolean>

Checks whether the current user is authenticated using the active server request context.

Intended for Server Components, Server Actions, Route Handlers, and Middleware where the request is implicitly available.

Returns

Promise<boolean>

Returns true if a valid session exists; otherwise false.

Examples

src/app/page.tsx
import { isAuthenticated } from "@monocloud/auth-nextjs";

export default async function Home() {
  const authenticated = await isAuthenticated();

  return <div>Authenticated: {authenticated.toString()}</div>;
}

Call Signature

isAuthenticated(req: Request | NextRequest, res?: Response | NextResponse<unknown>): Promise<boolean>

Checks whether the current user is authenticated using an explicit Web or Next.js request.

Use this overload when you already have access to a Request or NextRequest (for example, in Middleware or Route Handlers).

Parameters

ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
res?Response | NextResponse<unknown>Optional response to update if refreshed authentication cookies or headers are required.

Returns

Promise<boolean>

Returns true if a valid session exists; otherwise false.

Examples

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

export default async function proxy(req: NextRequest) {
  const authenticated = await isAuthenticated(req);

  if (!authenticated) {
    return new NextResponse("User not signed in", { status: 401 });
  }

  return NextResponse.next();
}

Call Signature

isAuthenticated(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<boolean>

Checks whether the current user is authenticated in the Pages Router or Node.js runtime.

Use this overload in API routes or getServerSideProps, where Node.js request and response objects are available.

Parameters

ParameterTypeDescription
reqNextApiRequest | IncomingMessageIncoming Node.js request used to resolve authentication from cookies.
resNextApiResponse | ServerResponse<IncomingMessage>Outgoing Node.js response used to apply refreshed authentication cookies when required.

Returns

Promise<boolean>

Returns true if a valid session exists; otherwise false.

Examples

src/pages/index.tsx
import { isAuthenticated } from "@monocloud/auth-nextjs";
import { GetServerSideProps } from "next";

type Props = {
  authenticated: boolean;
};

export default function Home({ authenticated }: Props) {
  return <pre>User is {authenticated ? "logged in" : "guest"}</pre>;
}

export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
  const authenticated = await isAuthenticated(ctx.req, ctx.res);

  return {
    props: {
      authenticated
    }
  };
};
© 2024 MonoCloud. All rights reserved.