Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

next-auth

Package Overview
Dependencies
Maintainers
3
Versions
714
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-auth - npm Package Compare versions

Comparing version 0.0.0-manual.b7162c86 to 0.0.0-manual.c885ac1d

lib/actions.d.ts

278

index.d.ts

@@ -1,3 +0,277 @@

export * from "@auth/nextjs";
export { default } from "@auth/nextjs";
/**
*
* :::warning Note
* This is the documentation for `next-auth@latest`. Check out the documentation of v4 [here](https://next-auth.js.org).
* :::
*
* If you are looking for the migration guide, visit the [`next-auth@latest` Migration Guide](https://nextjs.authjs.dev/v5).
*
* ## Installation
*
* ```bash npm2yarn2pnpm
* npm install next-auth@5 @auth/core
* ```
*
* ## Signing in and signing out
*
* The App Router embraces Server Actions that can be leveraged to decrease the amount of JavaScript sent to the browser.
*
* ```ts title="app/auth-components.tsx"
* import { signIn, signOut } from "../auth"
*
* export function SignIn({ provider, ...props }: any) {
* return (
* <form action={signIn(provider)}>
* <button {{...props}}/>
* </form>
* )
* }
*
* export function SignOut(props: any) {
* return (
* <form action={signOut}>
* <button {...props}/>
* </form>
* )
* }
* ```
*
* Alternatively, you can create client components, using the `signIn()` and `signOut` methods from the `next-auth/react` submodule:
*
* ```ts title="app/auth-components.tsx"
* "use client"
* import { signIn, signOut } from "next-auth/react"
*
* export function SignIn({provider, ...props}: any) {
* return <button {...props} onClick={() => signIn(provider)}/>
* }
*
* export function SignOut(props: any) {
* return <button {...props} onClick={() => signOut()}/>
* }
* ```
*
* Then, you could for example use it like this:
*
* ```ts title=app/page.tsx
* import { SignIn, SignOut } from "./auth-components"
*
* export default async function Page() {
* const session = await auth()
* if (session) {
* return (
* <>
* <pre>{JSON.stringify(session, null, 2)}</pre>
* <SignOut>Sign out</SignOut>
* </>
* )
* }
* return <SignIn provider="github">Sign in with GitHub</SignIn>
* }
* ```
*
*
* ## Environment variable inferrence
*
* `NEXTAUTH_URL` and `NEXTAUTH_SECRET` have been inferred since v4.
*
* Since NextAuth.js v5 can also automatically infer environment variables that are prefiexed with `AUTH_`.
*
* For example `AUTH_GITHUB_ID` and `AUTH_GITHUB_SECRET` will be used as the `clientId` and `clientSecret` options for the GitHub provider.
*
* :::tip
* The environment variable name inferring has the following format for OAuth providers: `AUTH_{PROVIDER}_{ID|SECRET}`.
*
* `PROVIDER` is the uppercase snake case version of the provider's id, followed by either `ID` or `SECRET` respectively.
* :::
*
* `AUTH_SECRET` and `AUTH_URL` are also aliased for `NEXTAUTH_SECRET` and `NEXTAUTH_URL` for consistency.
*
* To add social login to your app, the configuration becomes:
*
* ```ts title="auth.ts"
* import NextAuth from "next-auth"
* import GitHub from "next-auth/providers/GitHub"
* export const { handlers, auth } = NextAuth({ providers: [ GitHub ] })
* ```
*
* And the `.env.local` file:
*
* ```sh title=".env.local"
* AUTH_GITHUB_ID=...
* AUTH_GITHUB_SECRET=...
* AUTH_SECRET=...
* ```
*
* :::tip
* In production, `AUTH_SECRET` is a required environment variable - if not set, NextAuth.js will throw an error. See [MissingSecretError](https://authjs.dev/reference/core/errors#missingsecret) for more details.
* :::
*
* If you need to override the default values for a provider, you can still call it as a function `GitHub({...})` as before.
*
* @module index
*/
import type { Account, Session, User } from "@auth/core/types";
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from "next";
import type { AppRouteHandlerFn } from "next/dist/server/future/route-modules/app-route/module.js";
import type { NextRequest } from "next/server";
import type { NextAuthConfig, NextAuthRequest } from "./lib/index.js";
export type { Account, DefaultSession, Profile, Session, User, } from "./types.js";
type AppRouteHandlers = Record<"GET" | "POST", (req: NextRequest) => Promise<Response>>;
export type { NextAuthConfig };
export interface AuthSession extends Session {
user: User;
accounts: Account[];
}
/**
* The result of invoking {@link NextAuth|NextAuth}, initialized with the {@link NextAuthConfig}.
* It contains methods to set up and interact with NextAuth.js in your Next.js app.
*/
export interface NextAuthResult {
/**
* The NextAuth.js [Route Handler](https://beta.nextjs.org/docs/routing/route-handlers) methods. These are used to expose an endpoint for OAuth/Email providers,
* as well as REST API endpoints (such as `/api/auth/session`) that can be contacted from the client.
*
* After initializing NextAuth.js in `auth.ts`,
* re-export these methods.
*
* In `app/api/auth/[...nextauth]/route.ts`:
*
* ```ts title="app/api/auth/[...nextauth]/route.ts"
* export { GET, POST } from "../../../../auth"
* export const runtime = "edge" // optional
* ```
* Then `auth.ts`:
* ```ts title="auth.ts"
* // ...
* export const { handlers: { GET, POST }, auth } = NextAuth({...})
* ```
*/
handlers: AppRouteHandlers;
/**
* A universal method to interact with NextAuth.js in your Next.js app.
* After initializing NextAuth.js in `auth.ts`, use this method in Middleware, Server Components, Route Handlers (`app/`), and Edge or Node.js API Routes (`pages/`).
*
* #### In Middleware
*
* :::info
* Adding `auth` to your Middleware is optional, but recommended to keep the user session alive.
* :::
*
* Authentication is done by the {@link NextAuthConfig.callbacks|callbacks.authorized} callback.
* @example
* ```ts title="middleware.ts"
* export { auth as middleware } from "./auth"
* ```
*
* Alternatively you can wrap your own middleware with `auth`, where `req` is extended with `auth`:
* @example
* ```ts title="middleware.ts"
* import { auth } from "./auth"
* export default auth((req) => {
* // req.auth
* })
* ```
*
* ```ts
* // Optionally, don't invoke Middleware on some paths
* // Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
* export const config = {
* matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
* }
* ```
*
* #### In Server Components
*
* @example
* ```ts title="app/page.ts"
* import { auth } from "../auth"
*
* export default async function Page() {
* const { user } = await auth()
* return <p>Hello {user?.name}</p>
* }
* ```
*
* #### In Route Handlers
* @example
* ```ts title="app/api/route.ts"
* import { auth } from "../../auth"
*
* export const POST = auth((req) => {
* // req.auth
* })
* ```
*
* #### In Edge API Routes
*
* @example
* ```ts title="pages/api/protected.ts"
* import { auth } from "../../auth"
*
* export default auth((req) => {
* // req.auth
* })
*
* export const config = { runtime: "edge" }
* ```
*
* #### In API Routes
*
* @example
* ```ts title="pages/api/protected.ts"
* import { auth } from "../auth"
* import type { NextApiRequest, NextApiResponse } from "next"
*
* export default async (req: NextApiRequest, res: NextApiResponse) => {
* const session = await auth(req, res)
* if (session) {
* // Do something with the session
* return res.json("This is protected content.")
* }
* res.status(401).json("You must be signed in.")
* }
* ```
*
* #### In `getServerSideProps`
*
* @example
* ```ts title="pages/protected-ssr.ts"
* import { auth } from "../auth"
* //...
* export const getServerSideProps: GetServerSideProps = async (context) => {
* const session = await auth(context)
*
* if (session) {
* // Do something with the session
* return { props: { session, content: (await res.json()).content } }
* }
*
* return { props: {} }
* }
* ```
*/
auth: ((...args: [NextApiRequest, NextApiResponse]) => Promise<AuthSession | null>) & ((...args: []) => Promise<AuthSession | null>) & ((...args: [GetServerSidePropsContext]) => Promise<AuthSession | null>) & ((...args: [(req: NextAuthRequest) => ReturnType<AppRouteHandlerFn>]) => AppRouteHandlerFn);
signIn: (provider: string, options?: {
redirectTo?: string;
redirect?: boolean;
}) => (formData?: FormData) => Promise<string | never> | void;
signOut: (options?: {
redirectTo?: string;
redirect?: boolean;
}) => (formData?: FormData) => Promise<string | never> | void;
update: (data: Partial<AuthSession>) => Promise<AuthSession | null>;
}
/**
* Initialize NextAuth.js.
*
* @example
* ```ts title="auth.ts"
* import NextAuth from "next-auth"
* import GitHub from "@auth/core/providers/github"
*
* export const { handlers, auth } = NextAuth({ providers: [GitHub] })
* ```
*/
export default function NextAuth(config: NextAuthConfig): NextAuthResult;
//# sourceMappingURL=index.d.ts.map

@@ -1,2 +0,150 @@

export * from "@auth/nextjs";
export { default } from "@auth/nextjs";
/**
*
* :::warning Note
* This is the documentation for `next-auth@latest`. Check out the documentation of v4 [here](https://next-auth.js.org).
* :::
*
* If you are looking for the migration guide, visit the [`next-auth@latest` Migration Guide](https://nextjs.authjs.dev/v5).
*
* ## Installation
*
* ```bash npm2yarn2pnpm
* npm install next-auth@5 @auth/core
* ```
*
* ## Signing in and signing out
*
* The App Router embraces Server Actions that can be leveraged to decrease the amount of JavaScript sent to the browser.
*
* ```ts title="app/auth-components.tsx"
* import { signIn, signOut } from "../auth"
*
* export function SignIn({ provider, ...props }: any) {
* return (
* <form action={signIn(provider)}>
* <button {{...props}}/>
* </form>
* )
* }
*
* export function SignOut(props: any) {
* return (
* <form action={signOut}>
* <button {...props}/>
* </form>
* )
* }
* ```
*
* Alternatively, you can create client components, using the `signIn()` and `signOut` methods from the `next-auth/react` submodule:
*
* ```ts title="app/auth-components.tsx"
* "use client"
* import { signIn, signOut } from "next-auth/react"
*
* export function SignIn({provider, ...props}: any) {
* return <button {...props} onClick={() => signIn(provider)}/>
* }
*
* export function SignOut(props: any) {
* return <button {...props} onClick={() => signOut()}/>
* }
* ```
*
* Then, you could for example use it like this:
*
* ```ts title=app/page.tsx
* import { SignIn, SignOut } from "./auth-components"
*
* export default async function Page() {
* const session = await auth()
* if (session) {
* return (
* <>
* <pre>{JSON.stringify(session, null, 2)}</pre>
* <SignOut>Sign out</SignOut>
* </>
* )
* }
* return <SignIn provider="github">Sign in with GitHub</SignIn>
* }
* ```
*
*
* ## Environment variable inferrence
*
* `NEXTAUTH_URL` and `NEXTAUTH_SECRET` have been inferred since v4.
*
* Since NextAuth.js v5 can also automatically infer environment variables that are prefiexed with `AUTH_`.
*
* For example `AUTH_GITHUB_ID` and `AUTH_GITHUB_SECRET` will be used as the `clientId` and `clientSecret` options for the GitHub provider.
*
* :::tip
* The environment variable name inferring has the following format for OAuth providers: `AUTH_{PROVIDER}_{ID|SECRET}`.
*
* `PROVIDER` is the uppercase snake case version of the provider's id, followed by either `ID` or `SECRET` respectively.
* :::
*
* `AUTH_SECRET` and `AUTH_URL` are also aliased for `NEXTAUTH_SECRET` and `NEXTAUTH_URL` for consistency.
*
* To add social login to your app, the configuration becomes:
*
* ```ts title="auth.ts"
* import NextAuth from "next-auth"
* import GitHub from "next-auth/providers/GitHub"
* export const { handlers, auth } = NextAuth({ providers: [ GitHub ] })
* ```
*
* And the `.env.local` file:
*
* ```sh title=".env.local"
* AUTH_GITHUB_ID=...
* AUTH_GITHUB_SECRET=...
* AUTH_SECRET=...
* ```
*
* :::tip
* In production, `AUTH_SECRET` is a required environment variable - if not set, NextAuth.js will throw an error. See [MissingSecretError](https://authjs.dev/reference/core/errors#missingsecret) for more details.
* :::
*
* If you need to override the default values for a provider, you can still call it as a function `GitHub({...})` as before.
*
* @module index
*/
import { Auth } from "@auth/core";
import { reqWithEnvUrl, setEnvDefaults } from "./lib/env.js";
import { initAuth } from "./lib/index.js";
import { signIn, signOut, update } from "./lib/actions.js";
/**
* Initialize NextAuth.js.
*
* @example
* ```ts title="auth.ts"
* import NextAuth from "next-auth"
* import GitHub from "@auth/core/providers/github"
*
* export const { handlers, auth } = NextAuth({ providers: [GitHub] })
* ```
*/
export default function NextAuth(config) {
setEnvDefaults(config);
const httpHandler = (req) => Auth(reqWithEnvUrl(req), config);
return {
handlers: { GET: httpHandler, POST: httpHandler },
// @ts-expect-error
auth: initAuth(config),
signIn(provider, options) {
return async () => {
"use server";
return signIn(provider, options, config);
};
},
signOut(options) {
return async () => {
"use server";
return signOut(options, config);
};
},
update: (data) => update(data, config),
};
}

@@ -1,2 +0,9 @@

export * from "@auth/nextjs/jwt";
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module jwt
*/
export {};
//# sourceMappingURL=jwt.d.ts.map

@@ -1,1 +0,12 @@

export * from "@auth/nextjs/jwt";
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module jwt
*/
throw new ReferenceError([
'"next-auth/jwt" is deprecated. If you are not ready to migrate, keep using "next-auth@4".',
"Read more on https://nextjs.authjs.dev/v5",
].join("\n"));
export {};

@@ -1,2 +0,9 @@

export * from "@auth/nextjs/middleware";
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module middleware
*/
export {};
//# sourceMappingURL=middleware.d.ts.map

@@ -1,1 +0,12 @@

export * from "@auth/nextjs/middleware";
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module middleware
*/
throw new ReferenceError([
'"next-auth/middleware" is deprecated. If you are not ready to migrate, keep using "next-auth@4".',
"Read more on https://nextjs.authjs.dev/v5",
].join("\n"));
export {};

78

package.json
{
"name": "next-auth",
"version": "0.0.0-manual.b7162c86",
"version": "0.0.0-manual.c885ac1d",
"description": "Authentication for Next.js",
"homepage": "https://next-auth.js.org",
"homepage": "https://nextjs.authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth.git",
"author": "Iain Collins <me@iaincollins.com>",
"author": "Balázs Orbán <info@balazsorban.com>",
"contributors": [
"Balázs Orbán <info@balazsorban.com>",
"Iain Collins <me@iaincollins.com>",
"Nico Domino <yo@ndo.dev>",
"Lluis Agusti <hi@llu.lu>",
"Thang Huu Vu <thvu@hey.com>"
"Thang Huu Vu <hi@thvu.dev>"
],
"type": "module",
"types": "./index.d.ts",
"exports": {

@@ -21,5 +20,2 @@ ".": {

},
"./adapters": {
"types": "./adapters.d.ts"
},
"./jwt": {

@@ -44,5 +40,5 @@ "types": "./jwt.d.ts",

},
"./client": {
"types": "./client.d.ts",
"import": "./client.js"
"./react": {
"types": "./react.d.ts",
"import": "./react.js"
},

@@ -69,2 +65,3 @@ "./types": {

"*.js",
"lib",
"providers",

@@ -75,10 +72,8 @@ "src"

"dependencies": {
"@auth/core": "0.8.2",
"@auth/nextjs": "0.0.1"
"@auth/core": "experimental"
},
"peerDependencies": {
"next": "^13.4.5",
"next": "^13.5.3",
"nodemailer": "^6.6.5",
"react": "^17.0.2 || ^18",
"react-dom": "^17.0.2 || ^18"
"react": "^18.2.0"
},

@@ -91,49 +86,14 @@ "peerDependenciesMeta": {

"devDependencies": {
"@babel/cli": "^7.17.10",
"@babel/core": "^7.18.2",
"@babel/plugin-proposal-optional-catch-binding": "^7.16.7",
"@babel/plugin-transform-runtime": "^7.18.2",
"@babel/preset-env": "^7.18.2",
"@babel/preset-react": "^7.17.12",
"@babel/preset-typescript": "^7.17.12",
"@edge-runtime/jest-environment": "1.1.0-beta.35",
"@swc/core": "^1.2.198",
"@swc/jest": "^0.2.21",
"@testing-library/dom": "^8.13.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/react-hooks": "^8.0.0",
"@testing-library/user-event": "^14.2.0",
"@types/jest": "^28.1.3",
"@types/node": "^17.0.42",
"@types/nodemailer": "^6.4.4",
"@types/oauth": "^0.9.1",
"@types/react": "18.0.37",
"@types/react-dom": "^18.0.6",
"autoprefixer": "^10.4.7",
"babel-plugin-jsx-pragmatic": "^1.0.2",
"babel-preset-preact": "^2.0.0",
"concurrently": "^7",
"cssnano": "^5.1.11",
"jest": "^28.1.1",
"jest-environment-jsdom": "^28.1.1",
"jest-watch-typeahead": "^1.1.0",
"msw": "^0.42.3",
"next": "13.4.5",
"postcss": "^8.4.14",
"postcss-cli": "^9.1.0",
"postcss-nested": "^5.0.6",
"react": "^18",
"react-dom": "^18",
"whatwg-fetch": "^3.6.2",
"@next-auth/tsconfig": "0.0.0"
"next": "13.5.4-canary.4",
"nodemailer": "^6.9.3",
"react": "^18.2.0",
"typescript": "5.2.2"
},
"scripts": {
"build": "pnpm clean && pnpm providers && tsc",
"clean": "rm -rf coverage providers *.js *.d.ts*",
"dev": "pnpm clean && pnpm providers && tsc -w",
"lint": "eslint src config tests",
"providers": "node scripts/generate-providers",
"test": "jest --config ./config/jest.config.js"
"clean": "rm -rf *.js *.d.ts* lib providers",
"dev": "pnpm providers && tsc -w",
"providers": "node scripts/generate-providers"
}
}

@@ -1,2 +0,79 @@

export * from "@auth/nextjs/client";
/**
*
* Client-side methods for NextAuth.js.
*
* @module react
*/
import * as React from "react";
import type { BuiltInProviderType, RedirectableProviderType } from "@auth/core/providers";
import type { Session } from "@auth/core/types";
import type { LiteralUnion, SessionProviderProps, SignInAuthorizationParams, SignInOptions, SignInResponse, SignOutParams, SignOutResponse, UseSessionOptions } from "./lib/client.js";
export type { LiteralUnion, SignInOptions, SignInAuthorizationParams, SignOutParams, SignInResponse, };
export { SessionProviderProps };
/** @todo Document */
export type UpdateSession = (data?: any) => Promise<Session | null>;
/**
* useSession() returns an object containing three things: a method called {@link UpdateSession|update}, `data` and `status`.
*/
export type SessionContextValue<R extends boolean = false> = R extends true ? {
update: UpdateSession;
data: Session;
status: "authenticated";
} | {
update: UpdateSession;
data: null;
status: "loading";
} : {
update: UpdateSession;
data: Session;
status: "authenticated";
} | {
update: UpdateSession;
data: null;
status: "unauthenticated" | "loading";
};
export declare const SessionContext: React.Context<{
update: UpdateSession;
data: Session;
status: "authenticated";
} | {
update: UpdateSession;
data: null;
status: "unauthenticated" | "loading";
} | undefined>;
/**
* React Hook that gives you access to the logged in user's session data and lets you modify it.
*
* :::info
* You will likely not need `useSession` if you are using the [Next.js App Router (`app/`)](https://nextjs.org/blog/next-13-4#nextjs-app-router).
* :::
*/
export declare function useSession<R extends boolean>(options?: UseSessionOptions<R>): SessionContextValue<R>;
export interface GetSessionParams {
event?: "storage" | "timer" | "hidden" | string;
triggerEvent?: boolean;
broadcast?: boolean;
}
export declare function getSession(params?: GetSessionParams): Promise<Session | null>;
/**
* Initiate a signin flow or send the user to the signin page listing all possible providers.
* Handles CSRF protection.
*/
export declare function signIn<P extends RedirectableProviderType | undefined = undefined>(provider?: LiteralUnion<P extends RedirectableProviderType ? P | BuiltInProviderType : BuiltInProviderType>, options?: SignInOptions, authorizationParams?: SignInAuthorizationParams): Promise<P extends RedirectableProviderType ? SignInResponse | undefined : undefined>;
/**
* Initiate a signout, by destroying the current session.
* Handles CSRF protection.
*/
export declare function signOut<R extends boolean = true>(options?: SignOutParams<R>): Promise<R extends true ? undefined : SignOutResponse>;
/**
* [React Context](https://react.dev/learn/passing-data-deeply-with-context) provider to wrap the app (`pages/`) to make session data available anywhere.
*
* When used, the session state is automatically synchronized across all open tabs/windows and they are all updated whenever they gain or lose focus
* or the state changes (e.g. a user signs in or out) when {@link SessionProviderProps.refetchOnWindowFocus} is `true`.
*
* :::info
* You will likely not need `SessionProvider` if you are using the [Next.js App Router (`app/`)](https://nextjs.org/blog/next-13-4#nextjs-app-router).
* :::
*/
export declare function SessionProvider(props: SessionProviderProps): JSX.Element;
//# sourceMappingURL=react.d.ts.map

@@ -1,1 +0,347 @@

export * from "@auth/nextjs/client";
/**
*
* Client-side methods for NextAuth.js.
*
* @module react
*/
"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { apiBaseUrl, ClientSessionError, fetchData, now, parseUrl, useOnline, } from "./lib/client.js";
// This behaviour mirrors the default behaviour for getting the site name that
// happens server side in server/index.js
// 1. An empty value is legitimate when the code is being invoked client side as
// relative URLs are valid in that context and so defaults to empty.
// 2. When invoked server side the value is picked up from an environment
// variable and defaults to 'http://localhost:3000'.
const __NEXTAUTH = {
baseUrl: parseUrl(process.env.NEXTAUTH_URL ?? process.env.VERCEL_URL).origin,
basePath: parseUrl(process.env.NEXTAUTH_URL).path,
baseUrlServer: parseUrl(process.env.NEXTAUTH_URL_INTERNAL ??
process.env.NEXTAUTH_URL ??
process.env.VERCEL_URL).origin,
basePathServer: parseUrl(process.env.NEXTAUTH_URL_INTERNAL ?? process.env.NEXTAUTH_URL).path,
_lastSync: 0,
_session: undefined,
_getSession: () => { },
};
function broadcast() {
if (typeof BroadcastChannel !== "undefined") {
return new BroadcastChannel("next-auth");
}
return {
postMessage: () => { },
addEventListener: () => { },
removeEventListener: () => { },
};
}
// TODO:
const logger = {
debug: console.debug,
error: console.error,
warn: console.warn,
};
export const SessionContext = React.createContext?.(undefined);
/**
* React Hook that gives you access to the logged in user's session data and lets you modify it.
*
* :::info
* You will likely not need `useSession` if you are using the [Next.js App Router (`app/`)](https://nextjs.org/blog/next-13-4#nextjs-app-router).
* :::
*/
export function useSession(options) {
if (!SessionContext) {
throw new Error("React Context is unavailable in Server Components");
}
// @ts-expect-error Satisfy TS if branch on line below
const value = React.useContext(SessionContext);
if (!value && process.env.NODE_ENV !== "production") {
throw new Error("[next-auth]: `useSession` must be wrapped in a <SessionProvider />");
}
const { required, onUnauthenticated } = options ?? {};
const requiredAndNotLoading = required && value.status === "unauthenticated";
React.useEffect(() => {
if (requiredAndNotLoading) {
const url = `/api/auth/signin?${new URLSearchParams({
error: "SessionRequired",
callbackUrl: window.location.href,
})}`;
if (onUnauthenticated)
onUnauthenticated();
else
window.location.href = url;
}
}, [requiredAndNotLoading, onUnauthenticated]);
if (requiredAndNotLoading) {
return {
data: value.data,
update: value.update,
status: "loading",
};
}
return value;
}
export async function getSession(params) {
const session = await fetchData("session", __NEXTAUTH, logger, params);
if (params?.broadcast ?? true) {
broadcast().postMessage({
event: "session",
data: { trigger: "getSession" },
});
}
return session;
}
/**
* Returns the current Cross-Site Request Forgery Token (CSRF Token)
* required to make requests that changes state. (e.g. signing in or out, or updating the session).
*
* [CSRF Prevention: Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie)
* @internal
*/
export async function getCsrfToken() {
const response = await fetchData("csrf", __NEXTAUTH, logger);
return response?.csrfToken;
}
/**
* Returns a client-safe configuration object of the currently
* available providers.
* @internal
*/
export async function getProviders() {
return fetchData("providers", __NEXTAUTH, logger);
}
/**
* Initiate a signin flow or send the user to the signin page listing all possible providers.
* Handles CSRF protection.
*/
export async function signIn(provider, options, authorizationParams) {
const { callbackUrl = window.location.href, redirect = true } = options ?? {};
const baseUrl = apiBaseUrl(__NEXTAUTH);
const providers = await getProviders();
if (!providers) {
window.location.href = `${baseUrl}/error`;
return;
}
if (!provider || !(provider in providers)) {
window.location.href = `${baseUrl}/signin?${new URLSearchParams({
callbackUrl,
})}`;
return;
}
const isCredentials = providers[provider].type === "credentials";
const isEmail = providers[provider].type === "email";
const isSupportingReturn = isCredentials || isEmail;
const signInUrl = `${baseUrl}/${isCredentials ? "callback" : "signin"}/${provider}`;
const _signInUrl = `${signInUrl}?${new URLSearchParams(authorizationParams)}`;
const res = await fetch(_signInUrl, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
// @ts-expect-error
body: new URLSearchParams({
...options,
csrfToken: await getCsrfToken(),
callbackUrl,
}),
});
const data = await res.json();
// TODO: Do not redirect for Credentials and Email providers by default in next major
if (redirect || !isSupportingReturn) {
const url = data.url ?? callbackUrl;
window.location.href = url;
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes("#"))
window.location.reload();
return;
}
const error = new URL(data.url).searchParams.get("error");
if (res.ok) {
await __NEXTAUTH._getSession({ event: "storage" });
}
return {
error,
status: res.status,
ok: res.ok,
url: error ? null : data.url,
};
}
/**
* Initiate a signout, by destroying the current session.
* Handles CSRF protection.
*/
export async function signOut(options) {
const { callbackUrl = window.location.href } = options ?? {};
const baseUrl = apiBaseUrl(__NEXTAUTH);
const fetchOptions = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
// @ts-expect-error
body: new URLSearchParams({
csrfToken: await getCsrfToken(),
callbackUrl,
}),
};
const res = await fetch(`${baseUrl}/signout`, fetchOptions);
const data = await res.json();
broadcast().postMessage({ event: "session", data: { trigger: "signout" } });
if (options?.redirect ?? true) {
const url = data.url ?? callbackUrl;
window.location.href = url;
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes("#"))
window.location.reload();
// @ts-expect-error
return;
}
await __NEXTAUTH._getSession({ event: "storage" });
return data;
}
/**
* [React Context](https://react.dev/learn/passing-data-deeply-with-context) provider to wrap the app (`pages/`) to make session data available anywhere.
*
* When used, the session state is automatically synchronized across all open tabs/windows and they are all updated whenever they gain or lose focus
* or the state changes (e.g. a user signs in or out) when {@link SessionProviderProps.refetchOnWindowFocus} is `true`.
*
* :::info
* You will likely not need `SessionProvider` if you are using the [Next.js App Router (`app/`)](https://nextjs.org/blog/next-13-4#nextjs-app-router).
* :::
*/
export function SessionProvider(props) {
if (!SessionContext) {
throw new Error("React Context is unavailable in Server Components");
}
const { children, basePath, refetchInterval, refetchWhenOffline } = props;
if (basePath)
__NEXTAUTH.basePath = basePath;
/**
* If session was `null`, there was an attempt to fetch it,
* but it failed, but we still treat it as a valid initial value.
*/
const hasInitialSession = props.session !== undefined;
/** If session was passed, initialize as already synced */
__NEXTAUTH._lastSync = hasInitialSession ? now() : 0;
const [session, setSession] = React.useState(() => {
if (hasInitialSession)
__NEXTAUTH._session = props.session;
return props.session;
});
/** If session was passed, initialize as not loading */
const [loading, setLoading] = React.useState(!hasInitialSession);
React.useEffect(() => {
__NEXTAUTH._getSession = async ({ event } = {}) => {
try {
const storageEvent = event === "storage";
// We should always update if we don't have a client session yet
// or if there are events from other tabs/windows
if (storageEvent || __NEXTAUTH._session === undefined) {
__NEXTAUTH._lastSync = now();
__NEXTAUTH._session = await getSession({
broadcast: !storageEvent,
});
setSession(__NEXTAUTH._session);
return;
}
if (
// If there is no time defined for when a session should be considered
// stale, then it's okay to use the value we have until an event is
// triggered which updates it
!event ||
// If the client doesn't have a session then we don't need to call
// the server to check if it does (if they have signed in via another
// tab or window that will come through as a "stroage" event
// event anyway)
__NEXTAUTH._session === null ||
// Bail out early if the client session is not stale yet
now() < __NEXTAUTH._lastSync) {
return;
}
// An event or session staleness occurred, update the client session.
__NEXTAUTH._lastSync = now();
__NEXTAUTH._session = await getSession();
setSession(__NEXTAUTH._session);
}
catch (error) {
logger.error(new ClientSessionError(error.message, error));
}
finally {
setLoading(false);
}
};
__NEXTAUTH._getSession();
return () => {
__NEXTAUTH._lastSync = 0;
__NEXTAUTH._session = undefined;
__NEXTAUTH._getSession = () => { };
};
}, []);
React.useEffect(() => {
const handle = () => __NEXTAUTH._getSession({ event: "storage" });
// Listen for storage events and update session if event fired from
// another window (but suppress firing another event to avoid a loop)
// Fetch new session data but tell it to not to fire another event to
// avoid an infinite loop.
// Note: We could pass session data through and do something like
// `setData(message.data)` but that can cause problems depending
// on how the session object is being used in the client; it is
// more robust to have each window/tab fetch it's own copy of the
// session object rather than share it across instances.
broadcast().addEventListener("message", handle);
return () => broadcast().removeEventListener("message", handle);
}, []);
React.useEffect(() => {
const { refetchOnWindowFocus = true } = props;
// Listen for when the page is visible, if the user switches tabs
// and makes our tab visible again, re-fetch the session, but only if
// this feature is not disabled.
const visibilityHandler = () => {
if (refetchOnWindowFocus && document.visibilityState === "visible")
__NEXTAUTH._getSession({ event: "visibilitychange" });
};
document.addEventListener("visibilitychange", visibilityHandler, false);
return () => document.removeEventListener("visibilitychange", visibilityHandler, false);
}, [props.refetchOnWindowFocus]);
const isOnline = useOnline();
// TODO: Flip this behavior in next major version
const shouldRefetch = refetchWhenOffline !== false || isOnline;
React.useEffect(() => {
if (refetchInterval && shouldRefetch) {
const refetchIntervalTimer = setInterval(() => {
if (__NEXTAUTH._session) {
__NEXTAUTH._getSession({ event: "poll" });
}
}, refetchInterval * 1000);
return () => clearInterval(refetchIntervalTimer);
}
}, [refetchInterval, shouldRefetch]);
const value = React.useMemo(() => ({
data: session,
status: loading
? "loading"
: session
? "authenticated"
: "unauthenticated",
async update(data) {
if (loading || !session)
return;
setLoading(true);
const newSession = await fetchData("session", __NEXTAUTH, logger, typeof data === "undefined"
? undefined
: { body: { csrfToken: await getCsrfToken(), data } });
setLoading(false);
if (newSession) {
setSession(newSession);
broadcast().postMessage({
event: "session",
data: { trigger: "getSession" },
});
}
return newSession;
},
}), [session, loading]);
return (_jsx(SessionContext.Provider, { value: value, children: children }));
}
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img width="150px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>
<h3 align="center">NextAuth.js</h3>
<p align="center">Authentication for Next.js</p>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
<a href="https://authjs.dev" target="_blank"><img width="150px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>
<h3 align="center">NextAuth.js</a></h3>
<h4 align="center">Authentication for Next.js.</h4>
<p align="center" style="align: center;">
<a href="https://github.com/nextauthjs/next-auth/actions/workflows/release.yml?query=workflow%3ARelease">
<img src="https://github.com/nextauthjs/next-auth/actions/workflows/release.yml/badge.svg" alt="Release" />
<a href="https://npm.im/next-auth">
<img src="https://img.shields.io/badge/TypeScript-blue?style=flat-square" alt="TypeScript" />
</a>
<a href="https://packagephobia.com/result?p=next-auth">
<img src="https://packagephobia.com/badge?p=next-auth" alt="Bundle Size"/>
<a href="https://npm.im/next-auth">
<img alt="npm" src="https://img.shields.io/npm/v/next-auth?color=green&label=next-auth&style=flat-square">
</a>
<a href="https://www.npmtrends.com/next-auth">
<img src="https://img.shields.io/npm/dm/next-auth" alt="Downloads" />
<img src="https://img.shields.io/npm/dm/next-auth?label=%20downloads&style=flat-square" alt="Downloads" />
</a>
<a href="https://github.com/nextauthjs/next-auth/stargazers">
<img src="https://img.shields.io/github/stars/nextauthjs/next-auth" alt="Github Stars" />
<img src="https://img.shields.io/github/stars/nextauthjs/next-auth?style=flat-square" alt="Github Stars" />
</a>
<a href="https://www.npmjs.com/package/next-auth">
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?label=latest" alt="Github Stable Release" />
</a>
</p>
</p>
## Overview
---
NextAuth.js is a complete open source authentication solution for [Next.js](http://nextjs.org/) applications.
It is designed from the ground up to support Next.js and Serverless.
This is a monorepo containing the following packages / projects:
1. The primary `next-auth` package
2. A development test application
3. All `@next-auth/*-adapter` packages
4. The documentation site
## Getting Started
```
npm install next-auth
```
The easiest way to continue getting started, is to follow the [getting started](https://next-auth.js.org/getting-started/example) section in our docs.
We also have a section of [tutorials](https://next-auth.js.org/tutorials) for those looking for more specific examples.
See [next-auth.js.org](https://next-auth.js.org) for more information and documentation.
## Features
### Flexible and easy to use
- Designed to work with any OAuth service, it supports OAuth 1.0, 1.0A and 2.0
- Built-in support for [many popular sign-in services](https://next-auth.js.org/providers)
- Supports email / passwordless authentication
- Supports stateless authentication with any backend (Active Directory, LDAP, etc)
- Supports both JSON Web Tokens and database sessions
- Designed for Serverless but runs anywhere (AWS Lambda, Docker, Heroku, etc…)
### Own your own data
NextAuth.js can be used with or without a database.
- An open source solution that allows you to keep control of your data
- Supports Bring Your Own Database (BYOD) and can be used with any database
- Built-in support for [MySQL, MariaDB, Postgres, Microsoft SQL Server, MongoDB and SQLite](https://next-auth.js.org/configuration/databases)
- Works great with databases from popular hosting providers
- Can also be used _without a database_ (e.g. OAuth + JWT)
### Secure by default
- Promotes the use of passwordless sign-in mechanisms
- Designed to be secure by default and encourage best practices for safeguarding user data
- Uses Cross-Site Request Forgery (CSRF) Tokens on POST routes (sign in, sign out)
- Default cookie policy aims for the most restrictive policy appropriate for each cookie
- When JSON Web Tokens are enabled, they are encrypted by default (JWE) with A256GCM
- Auto-generates symmetric signing and encryption keys for developer convenience
- Features tab/window syncing and session polling to support short lived sessions
- Attempts to implement the latest guidance published by [Open Web Application Security Project](https://owasp.org)
Advanced options allow you to define your own routines to handle controlling what accounts are allowed to sign in, for encoding and decoding JSON Web Tokens and to set custom cookie security policies and session properties, so you can control who is able to sign in and how often sessions have to be re-validated.
### TypeScript
NextAuth.js comes with built-in types. For more information and usage, check out
the [TypeScript section](https://next-auth.js.org/getting-started/typescript) in the documentation.
## Example
### Add API Route
```javascript
// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth"
import AppleProvider from "next-auth/providers/apple"
import GoogleProvider from "next-auth/providers/google"
import EmailProvider from "next-auth/providers/email"
export default NextAuth({
secret: process.env.SECRET,
providers: [
// OAuth authentication providers
AppleProvider({
clientId: process.env.APPLE_ID,
clientSecret: process.env.APPLE_SECRET,
}),
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
// Sign in with passwordless email link
EmailProvider({
server: process.env.MAIL_SERVER,
from: "<no-reply@example.com>",
}),
],
})
```
### Add React Hook
The `useSession()` React Hook in the NextAuth.js client is the easiest way to check if someone is signed in.
```javascript
import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {
const { data: session } = useSession()
if (session) {
return (
<>
Signed in as {session.user.email} <br />
<button onClick={() => signOut()}>Sign out</button>
</>
)
}
return (
<>
Not signed in <br />
<button onClick={() => signIn()}>Sign in</button>
</>
)
}
```
### Share/configure session state
Use the `<SessionProvider>` to allow instances of `useSession()` to share the session object across components. It also takes care of keeping the session updated and synced between tabs/windows.
```jsx title="pages/_app.js"
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
```
## Security
If you think you have found a vulnerability (or not sure) in NextAuth.js or any of the related packages (i.e. Adapters), we ask you to have a read of our [Security Policy](https://github.com/nextauthjs/next-auth/blob/main/SECURITY.md) to reach out responsibly. Please do not open Pull Requests/Issues/Discussions before consulting with us.
## Acknowledgments
[NextAuth.js is made possible thanks to all of its contributors.](https://next-auth.js.org/contributors)
<a href="https://github.com/nextauthjs/next-auth/graphs/contributors">
<img width="500px" src="https://contrib.rocks/image?repo=nextauthjs/next-auth" />
</a>
<div>
<a href="https://vercel.com?utm_source=nextauthjs&utm_campaign=oss"></a>
</div>
### Support
We're happy to announce we've recently created an [OpenCollective](https://opencollective.com/nextauth) for individuals and companies looking to contribute financially to the project!
<!--sponsors start-->
<table>
<tbody>
<tr>
<td align="center" valign="top">
<a href="https://vercel.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/14985020?v=4" alt="Vercel Logo" />
</a><br />
<div>Vercel</div><br />
<sub>🥉 Bronze Financial Sponsor <br /> ☁️ Infrastructure Support</sub>
</td>
<td align="center" valign="top">
<a href="https://prisma.io" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/17219288?v=4" alt="Prisma Logo" />
</a><br />
<div>Prisma</div><br />
<sub>🥉 Bronze Financial Sponsor</sub>
</td>
<td align="center" valign="top">
<a href="https://clerk.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/49538330?s=200&v=4" alt="Clerk Logo" />
</a><br />
<div>Clerk</div><br />
<sub>🥉 Bronze Financial Sponsor</sub>
</td>
<td align="center" valign="top">
<a href="https://lowdefy.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/47087496?s=200&v=4" alt="Lowdefy Logo" />
</a><br />
<div>Lowdefy</div><br />
<sub>🥉 Bronze Financial Sponsor</sub>
</td>
<td align="center" valign="top">
<a href="https://workos.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/47638084?s=200&v=4" alt="WorkOS Logo" />
</a><br />
<div>WorkOS</div><br />
<sub>🥉 Bronze Financial Sponsor</sub>
</td>
<td align="center" valign="top">
<a href="https://www.descope.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/97479186?v=4" alt="Descope Logo" />
</a><br />
<div>Descope</div><br />
<sub>🥉 Bronze Financial Sponsor</sub>
</td>
<td align="center" valign="top">
<a href="https://checklyhq.com" target="_blank">
<img width="128px" src="https://avatars.githubusercontent.com/u/25982255?v=4" alt="Checkly Logo" />
</a><br />
<div>Checkly</div><br />
<sub>☁️ Infrastructure Support</sub>
</td>
<td align="center" valign="top">
<a href="https://superblog.ai/" target="_blank">
<img width="128px" src="https://d33wubrfki0l68.cloudfront.net/cdc4a3833bd878933fcc131655878dbf226ac1c5/10cd6/images/logo_bolt_small.png" alt="superblog Logo" />
</a><br />
<div>superblog</div><br />
<sub>☁️ Infrastructure Support</sub>
</td>
</tr><tr></tr>
</tbody>
</table>
<br />
<!--sponsors end-->
## Contributing
We're open to all community contributions! If you'd like to contribute in any way, please first read
our [Contributing Guide](https://github.com/nextauthjs/.github/blob/main/CONTRIBUTING.md).
## License
ISC
Check out the documentation at [nextjs.authjs.dev](https://nextjs.authjs.dev).

@@ -1,1 +0,16 @@

export * from "@auth/nextjs/jwt"
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module jwt
*/
throw new ReferenceError(
[
'"next-auth/jwt" is deprecated. If you are not ready to migrate, keep using "next-auth@4".',
"Read more on https://nextjs.authjs.dev/v5",
].join("\n")
)
export {}

@@ -1,1 +0,16 @@

export * from "@auth/nextjs/middleware"
/**
* :::warning Deprecated
* This module is replaced in v5. Read more at: https://nextjs.authjs.dev/v5#authenticating-server-side
* :::
*
* @module middleware
*/
throw new ReferenceError(
[
'"next-auth/middleware" is deprecated. If you are not ready to migrate, keep using "next-auth@4".',
"Read more on https://nextjs.authjs.dev/v5",
].join("\n")
)
export {}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc