@auth/nextjs
Version:
Authentication for Next.js.
60 lines • 2.58 kB
TypeScript
import { type AuthConfig } from "@auth/core";
import { NextResponse } from "next/server";
import type { JWT } from "@auth/core/jwt";
import type { Awaitable, CallbacksOptions, User } from "@auth/core/types";
import type { NextFetchEvent, NextMiddleware, NextRequest } from "next/server";
/**
* Callbacks are asynchronous functions you can use to control what happens when an auth-related action is performed.
* Callbacks **allow you to implement access controls without a database** or to **integrate with external databases or APIs**.
*/
export interface NextAuthCallbacks extends Partial<CallbacksOptions> {
/**
* Invoked when a user needs authorization, using [Middleware](https://nextjs.org/docs/advanced-features/middleware).
*
* You can override this behavior by returning a {@link NextResponse}.
*
* @example
* ```ts title="app/auth.ts"
* ...
* async authorized({ request, auth, expires }) {
* const url = request.nextUrl
*
* if(request.method === "POST") {
* const { authToken } = (await request.json()) ?? {}
* // If the request has a valid auth token, it is authorized
* const valid = await validateAuthToken(authToken)
* if(valid) return true
* return NextResponse.json("Invalid auth token", { status: 401 })
* }
*
* // Logged in users are authenticated, otherwise redirect to login page
* return !!auth
* }
* ...
* ```
*/
authorized: (params: {
/** The request to be authorized. */
request: NextRequest;
/** The authenticated user or token, if any. */
auth: JWT | User | null;
/** The expiration date of the session. */
expires: string | null;
}) => Awaitable<boolean | NextResponse>;
}
/** Configure Next.js Auth. */
export interface NextAuthConfig extends AuthConfig {
callbacks?: NextAuthCallbacks;
}
export interface NextRequestWithAuth extends NextRequest {
auth: JWT | User | null;
}
type NextMiddlewareWithAuth = (request: NextRequestWithAuth, event: NextFetchEvent) => ReturnType<NextMiddleware>;
type WithAuthArgs = [NextRequestWithAuth, NextFetchEvent] | [NextMiddlewareWithAuth] | [Headers] | [];
export declare function initAuth(config: NextAuthConfig): (...args: WithAuthArgs) => Promise<{
expires: string;
data: AuthData;
} | null> | Promise<NextResponse> | ((request: NextRequestWithAuth, event: NextFetchEvent) => Promise<NextResponse>);
type AuthData = JWT | User | null;
export {};
//# sourceMappingURL=index.d.ts.map