### Successful Installation Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/pkg-manager.md Example output showing a successful dependency installation using `npx auth init next`. ```bash $ npx auth init next Scaffolding next project with npm at ./my-next-app... > npm install added 500 packages in 45s ``` -------------------------------- ### Example Usage for Installation Failure Handling Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This example demonstrates how to use the installation function within a try-catch block to log the failed command if the installation promise is rejected. ```javascript try { await install() } catch (error) { console.error(`Command failed: ${error.command}`) } ``` -------------------------------- ### Initialize Auth.js Project (Clone Example) Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Clone a full working example project for the specified framework. This is the recommended way to get started with a functional project. ```javascript import { action } from './commands/init.js' // Clone Next.js example project await action('next', { example: true }) // Clone SvelteKit example project await action('sveltekit', { example: true }) ``` -------------------------------- ### Provider Configuration Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Demonstrates accessing provider configuration and conditionally opening the setup URL or logging instructions. Useful for guiding users through OAuth provider setup. ```javascript const provider = providers.discord if (provider.setupUrl) { await open(provider.setupUrl) } if (provider.instructions) { console.log(markdownToAnsi(provider.instructions)) } ``` -------------------------------- ### Offline Fallback Installation Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/pkg-manager.md Example output demonstrating the offline fallback mechanism when internet connectivity is lost. ```bash $ (offline) $ npx auth init next Yellow: "You appear to be offline. Falling back to the local cache." > npm install --offline (uses cached packages) ``` -------------------------------- ### Provider Configuration with Setup Instructions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Example of configuring an OAuth provider with its name, setup URL, and detailed setup instructions in Markdown format. This is used when a provider requires specific setup steps. ```javascript providers.github = { name: "GitHub", setupUrl: "https://github.com/settings/applications/new", instructions: "1. Click on New Application..." } ``` -------------------------------- ### Install Dependencies Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/pkg-manager.md Use this function to install project dependencies. It handles environment setup and error reporting. ```javascript import { install } from '../lib/pkg-manager.js' try { await install() console.log('Dependencies installed') } catch (error) { console.error(`Failed: ${error.command}`) } ``` -------------------------------- ### Example Usage of Providers Object Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Demonstrates how to import and use the providers object to filter providers with setup instructions, check for instructions, and access provider information. ```javascript import { providers } from '../lib/meta.js' // List all providers with setup instructions const withSetup = Object.entries(providers) .filter(([, { setupUrl }]) => !!setupUrl) .map(([id, { name }]) => ({ id, name })) // Check if provider has setup instructions const hasInstructions = !!providers.github.setupUrl console.log(hasInstructions) // true // Access provider information const provider = providers['discord'] console.log(provider.name) // "Discord" console.log(provider.setupUrl) // "https://discord.com/developers/applications" ``` -------------------------------- ### Provider Configuration without Setup Instructions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Example of configuring an OAuth provider with only its name and an undefined setup URL. This is used for providers that do not require a specific setup URL or have straightforward integration. ```javascript providers.auth0 = { name: "Auth0", setupUrl: undefined } ``` -------------------------------- ### PackageManager Usage Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Shows how to use the `PackageManager` type to construct an installation command based on the detected package manager. Useful for CLI tools that need to interact with the project's package manager. ```javascript import { getPkgManager } from './lib/pkg-manager.js' const manager = getPkgManager() const installCmd = `${manager} install` ``` -------------------------------- ### GitHub Provider Configuration Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Example of configuring the GitHub provider with its name, setup URL, and detailed markdown instructions for setting up the OAuth application. ```javascript providers.github = { name: "GitHub", setupUrl: "https://github.com/settings/applications/new", instructions: "\n1. Set *Application name* (can be anything)\n2. Set *Homepage URL* (your business/website, but can be anything)\n3. Paste the redirect URI (on your clipboard) to *Authorization callback URL*\n4. Click *Register application*\n5. Paste the *Client ID* back here\n6. Click *Generate a new client secret*\n7. Paste the *Client secret* back here (Note: This is the only time you can see it)\n " } ``` -------------------------------- ### Configure OAuth Provider with Setup Instructions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Configure an OAuth provider like GitHub, including its name, a URL for setup instructions, and detailed steps for registering the application and obtaining credentials. ```javascript { name: "GitHub", setupUrl: "https://github.com/settings/applications/new", instructions: "\n1. Set *Application name* (can be anything)\n2. Set *Homepage URL* (your business/website, but can be anything)\n3. Paste the redirect URI (on your clipboard) to *Authorization callback URL*\n4. Click *Register application*\n5. Paste the *Client ID* back here\n6. Click *Generate a new client secret*\n7. Paste the *Client secret* back here\n " } ``` -------------------------------- ### Initialize New Project with NextAuth.js CLI Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Use these commands to set up a new project with NextAuth.js integration. The `--example` flag clones a starter template. ```bash npx auth init next --example ``` ```bash npx auth init express ``` ```bash npx auth init sveltekit --example ``` -------------------------------- ### install Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/pkg-manager.md Spawns a package manager installation process with appropriate environment variables and error handling. It automatically detects the package manager, checks online status, builds arguments, sets necessary environment variables, and spawns a child process for installation. The function resolves when the installation completes successfully or rejects if the package manager returns a non-zero exit code. ```APIDOC ## Function: install ```javascript export async function install() ``` ### Description Spawns a package manager installation process with appropriate environment variables and error handling. ### Parameters None. Uses the package manager determined by `getPkgManager()`. ### Return Type Returns `Promise`. Spawns child process and resolves when installation completes. ### Behavior 1. **Get Package Manager**: Calls `getPkgManager()` 2. **Check Online Status**: Calls `getOnline()` to check internet connectivity 3. **Build Arguments**: - Base: `["install"]` - If offline: adds `["--offline"]` flag 4. **Set Environment Variables**: - `ADBLOCK=1` — disable install-time ads - `NODE_ENV=development` — ensure dev dependencies installed (important for pnpm) - `DISABLE_OPENCOLLECTIVE=1` — disable OpenCollective fundraising prompts - Preserves existing env vars with spread operator 5. **Spawn Process**: Uses `child_process.spawn()` with `stdio: "inherit"` (show all output) 6. **Handle Completion**: - On success (code 0): resolves Promise - On failure: rejects with error object containing command string ### Throws | Error | Condition | |-------|-----------| | { command: string } | Package manager returns non-zero exit code | ### Return Type When Rejected ```javascript { command: "npm install" // or "pnpm install", etc. } ``` ### Example Usage ```javascript import { install } from '../lib/pkg-manager.js' try { await install() console.log('Dependencies installed') } catch (error) { console.error(`Failed: ${error.command}`) } ``` ### Environment Setup Details #### ADBLOCK=1 Prevents npm install-time advertisements (eco-friendly package promotions, etc.) #### NODE_ENV=development Critical for pnpm: by default pnpm skips dev dependencies when NODE_ENV=production. The CLI sets development to ensure test/build tools are installed. #### DISABLE_OPENCOLLECTIVE=1 OpenCollective promotion messages appear during npm/yarn install. This suppresses them to avoid cluttering the CLI output. ### Online Detection When online status check fails, adds `--offline` flag to use cached packages. This requires that packages were previously installed locally. ### Output Handling All output from the installation process (stdout/stderr) is inherited to the parent process, so users see: - Download progress - Warnings and errors - Success messages - All interactive prompts ### Process Spawning Details ```javascript const child = spawn(packageManager, args, { stdio: "inherit", // Show all output env: { ...process.env, ADBLOCK: "1", NODE_ENV: "development", DISABLE_OPENCOLLECTIVE: "1" } }) ``` ### Exit Code Handling The promise resolves or rejects based on the child process exit code: ```javascript child.on("close", (code) => { if (code !== 0) { reject({ command: `${packageManager} ${args.join(" ")}` }) } else { resolve() } }) ``` ### Example Execution #### Successful Installation ```bash $ npx auth init next Scaffolding next project with npm at ./my-next-app... > npm install added 500 packages in 45s ``` #### Offline Fallback ```bash $ (offline) $ npx auth init next Yellow: "You appear to be offline. Falling back to the local cache." > npm install --offline (uses cached packages) ``` ### Source `lib/pkg-manager.js:39-70` ### Attribution Implementation adapted from Vercel's create-next-app: - https://github.com/vercel/next.js/blob/canary/packages/create-next-app/helpers/get-pkg-manager.ts - https://github.com/vercel/next.js/blob/canary/packages/create-next-app/helpers/install.ts ### Notes - Process inherits stdio, so user sees real-time output - Offline detection is automatic but can fail gracefully - NODE_ENV=development is important for correct dependency installation - Each call to install() spawns a new child process ``` -------------------------------- ### Retry Installation with User Feedback Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This pattern provides feedback to the user when an installation fails, suggesting a manual retry command. ```javascript try { await install() } catch (error) { console.error(`Installation failed: ${error.command}`) console.log("Try running manually: npm install") } ``` -------------------------------- ### Validate Provider Setup Instructions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This pattern checks if a provider has setup instructions available before proceeding, displaying an error message if not. ```javascript const provider = providers[providerId] if (!provider?.setupUrl) { console.error(y.red(`Provider ${providerId} has no setup instructions`)) return } ``` -------------------------------- ### Framework Configuration Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Demonstrates how to access framework configuration and construct a callback URL using its properties. This is useful for generating OAuth callback URLs dynamically. ```javascript const nextConfig = frameworks.next const callbackUrl = new URL( `${nextConfig.path}/callback/github`, `http://localhost:${nextConfig.port}` ) ``` -------------------------------- ### Internal Function: createFromExample Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Internal function to clone a framework example repository and optionally initialize AUTH_SECRET. This is used when the `--example` flag is provided. ```javascript async function createFromExample(framework, dir) ``` -------------------------------- ### Add Command Usage Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/add-command.md Examples of how to use the 'add' command in your project, both interactively and with specific providers. ```APIDOC ## Add Command ### Description The `add` command guides users through setting up a new OAuth provider in an existing Auth.js project. It handles provider-specific setup instructions, credential collection, and environment variable management. ### Function Signature ```javascript export async function action(providerId) ``` ### Parameters #### Path Parameters - **providerId** (string) - Optional - OAuth provider identifier (apple, github, google, discord, etc.). If omitted, user selects from available providers. ### Behavior 1. **Provider Selection**: If `providerId` not provided, interactive dropdown shows providers that have setup instructions. 2. **Framework Detection**: Uses `requireFramework()` to detect the project framework (fails if unknown). 3. **Display Setup Info**: Shows provider setup URL and callback URL (copied to clipboard). 4. **Open Browser**: Waits 3 seconds then opens provider setup URL in default browser. 5. **Provider-Specific Flow**: - **Apple**: Prompts for Client ID, Key ID, Team ID, Private Key path, and expiry (default 180 days). - Generates JWT-based client secret via `appleGenSecret()`. - Writes both ID and secret to .env. - **Other Providers**: Prompts for Client ID and Client Secret. - Writes `AUTH_{PROVIDER}_ID` and `AUTH_{PROVIDER}_SECRET` to .env. 6. **Success Message**: Displays "🎉 Done!" message upon completion. ### Throws - Error: Provider has no setup URL or instructions. - Error: User force closed prompts. - Error: Framework detection fails (via `requireFramework()`). - Error: Apple secret generation fails. - Error: .env file write fails. ### Example Usage (JavaScript) ```javascript import { action } from './commands/add.js' // Interactive: select provider await action() // Add GitHub provider await action('github') // Add Google provider await action('google') // Add Apple provider (special handling for JWT secret) await action('apple') // Add Discord provider await action('discord') ``` ### Example Usage (CLI) ```bash auth add auth add github auth add google auth add apple auth add discord auth add twitter ``` ### Environment Variable Naming **Standard Providers:** - Client ID: `AUTH_{PROVIDER_UPPERCASE}_ID` - Client Secret: `AUTH_{PROVIDER_UPPERCASE}_SECRET` **Apple (Special):** - Client ID: `AUTH_APPLE_ID` - Client Secret: `AUTH_APPLE_SECRET` (generated JWT) ### Callback URL Format Constructed from framework config: ``` http://localhost:{framework.port}{framework.path}/callback/{providerId} ``` ``` -------------------------------- ### Install Auth.js CLI Source: https://github.com/nextauthjs/cli/blob/main/README.md Run this command to execute the Auth.js CLI without a global installation. Supports various package managers. ```sh npx auth # or pnpx, bunx, yarn dlx, etc. ``` -------------------------------- ### Example Usage of appleGenSecret Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Demonstrates how to use the `appleGenSecret` function with the required `AppleGenSecretOptions`. Ensure the `privateKey` path is correct and all properties are provided. ```javascript const secret = await appleGenSecret({ teamId: "ABC123DEF", clientId: "com.example.app.service", keyId: "ABCDEFG123", privateKey: "./private-key.p8", expiresInDays: 180 }) ``` -------------------------------- ### Example Output Session Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/write-env.md Simulates an output session from the CLI, showing the messages generated when adding or updating environment variables. ```bash $ npx auth secret $ npx auth add github ✨ Updated `AUTH_SECRET` in .env.local. ➕ Added `AUTH_GITHUB_ID` to .env.local. ➕ Added `AUTH_GITHUB_SECRET` to .env.local. ``` -------------------------------- ### Example Usage of Framework Metadata Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Demonstrates how to import and access metadata for a specific framework, such as Next.js, from the frameworks object. ```javascript import { frameworks } from '../lib/meta.js' const framework = frameworks['next'] console.log(framework.name) // "Next.js" console.log(framework.envFile) // ".env.local" console.log(framework.port) // 3000 ``` -------------------------------- ### Configure OAuth Provider without Setup Instructions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Configure an OAuth provider like Auth0 where the setup URL is undefined. This indicates that the CLI's `add` command cannot be used interactively for this provider. ```javascript { name: "Auth0", setupUrl: undefined } ``` -------------------------------- ### Console Output Example (Non-Raw) Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/secret-command.md Example of the formatted output when the secret is generated and either copied to the clipboard or logged to the console if clipboard is unavailable. ```text Secret generated. It has been copied to your clipboard, paste it to your .env/.env.local file to continue. AUTH_SECRET="base64_value_here" ``` -------------------------------- ### Console Output Example (Clipboard Unavailable) Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/secret-command.md Example of the output when clipboard functionality is unavailable, prompting the user to manually copy the secret to their .env/.env.local file. ```text Secret generated. Copy it to your .env/.env.local file (depending on your framework): AUTH_SECRET="base64_value_here" ``` -------------------------------- ### Framework Configuration Function Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md An example of how to use the SupportedFramework type in a JSDoc annotation to ensure type safety when referencing framework configurations. ```javascript /** * @param {import("./meta").SupportedFramework} framework */ function getFrameworkConfig(framework) { return frameworks[framework] } ``` -------------------------------- ### Package Manager Detection Example Values Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md These are example values for the npm_config_user_agent environment variable, used to detect the package manager. ```text npm/9.2.0 node/18.0.0 ``` ```text pnpm/8.0.0 ``` ```text yarn/3.5.0 ``` ```text bun/1.0.0 ``` -------------------------------- ### Example Usage of the Add Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/add-command.md Demonstrates how to use the 'action' function programmatically to add different OAuth providers. This includes interactive selection, adding specific providers like GitHub, Google, Apple, and Discord. ```javascript import { action } from './commands/add.js' // Interactive: select provider await action() // Add GitHub provider await action('github') // Add Google provider await action('google') // Add Apple provider (special handling for JWT secret) await action('apple') // Add Discord provider await action('discord') ``` -------------------------------- ### Provider Setup Configuration Structure Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/add-command.md Defines the structure for provider configuration within Auth.js, including display name, setup URL, and step-by-step instructions. ```javascript { name: "Display Name", setupUrl: "https://...", instructions: "Step-by-step Markdown" } ``` -------------------------------- ### Providers Object Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md An example of the exported providers object, showing a partial list of available OAuth/OIDC providers. ```javascript export const providers = { "42-school", apple, asgardeo, auth0, ... (90+ providers) } ``` -------------------------------- ### Setting HTTPS Proxy and Running CLI Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Example of setting the https_proxy environment variable to configure a proxy for the CLI, followed by the command to initialize authentication. ```bash export https_proxy=http://proxy.corp.com:3128 npx auth init ``` -------------------------------- ### Callback URL Format Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/add-command.md Illustrates the format of the callback URL, which is dynamically constructed based on the framework's configuration and the provider ID. ```javascript // Constructed from framework config: // `http://localhost:{framework.port}{framework.path}/callback/{providerId}` // Examples: // - Next.js + GitHub: `http://localhost:3000/api/auth/callback/github` // - SvelteKit + Google: `http://localhost:5173/auth/callback/google` // - Express + Discord: `http://localhost:3000/auth/callback/discord` ``` -------------------------------- ### CLI Usage for Init Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Command-line interface commands to initialize an Auth.js project, with options to specify framework and clone examples. ```bash auth init auth init next auth init express auth init sveltekit --example auth init [framework] -e ``` -------------------------------- ### NextAuth.js CLI Usage Summary Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Overview of the NextAuth.js CLI structure, including available options, commands, and example usage patterns for quick reference. ```bash Usage: auth [options] [command] Options: -V, --version output the version number -h, --help display help for command Commands: ask [options] Ask about docs, API, or auth concepts init [options] [framework] Initialize a project secret [options] Generate a random string and add to .env add [provider] Register a new authentication provider help [command] display help for command Examples: auth ask # Interactive Q&A auth ask --stream # Stream response auth init next --example # Clone Next.js example auth secret --copy # Copy to clipboard auth add github # Setup GitHub OAuth ``` -------------------------------- ### SupportedFramework Usage Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Demonstrates how to use the `SupportedFramework` type after detecting the project's framework. Ensures type safety when handling framework-specific logic. ```javascript import { detectFramework } from './lib/detect.js' const framework = await detectFramework() if (framework !== "unknown") { // framework is now typed as "next" | "express" | "sveltekit" } ``` -------------------------------- ### Handle Package Manager Installation Failures Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This code implements a Promise that wraps the package manager's spawn process, rejecting the promise with a command signature if the process exits with a non-zero code. ```javascript return new Promise((resolve, reject) => { const child = spawn(packageManager, args, { stdio: "inherit" }) child.on("close", (code) => { if (code !== 0) { reject({ command: `${packageManager} ${args.join(" ")}` }) } else { resolve() } }) }) ``` -------------------------------- ### Apple Sign-In Environment Variables Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Example environment variables for Apple Sign-In, including the client ID and the JWT token for authentication. ```dotenv AUTH_APPLE_ID="com.example.app.service" AUTH_APPLE_SECRET="JWT_TOKEN_HERE" ``` -------------------------------- ### JSDoc Type Annotation Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md An example demonstrating how to use JSDoc type annotations for function parameters and return types. This helps IDEs provide type checking and autocompletion. ```javascript /** * @param {SupportedFramework} framework * @returns {Promise} */ export async function getConfig(framework) { return frameworks[framework]?.envFile || '.env' } ``` -------------------------------- ### Example package.json with Multiple Frameworks Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This JSON structure illustrates a `package.json` file containing dependencies for both Next.js and Express. This condition triggers the 'Multiple Frameworks Detected' error in the Auth.js CLI. ```json { "dependencies": { "next": "14.0.0", "express": "4.18.0" } } ``` -------------------------------- ### SvelteKit Framework Metadata Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Configuration details for the SvelteKit framework, including its name, example repository, demo URL, callback path, development port, and environment file. ```javascript sveltekit: { name: "SvelteKit", src: "https://github.com/nextauthjs/sveltekit-auth-example", demo: "https://sveltekit-auth-example.vercel.app", path: "/auth", port: 5173, envFile: ".env" } ``` -------------------------------- ### Detailed Example of breakStringToLines Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/markdown.md Illustrates the output of breakStringToLines with a sample sentence and a line limit of 30 characters, showing how the text is wrapped. ```javascript const text = "The quick brown fox jumps over the lazy dog and runs away" const lines = breakStringToLines(text, 30) console.log(lines) ``` -------------------------------- ### Example Usage of breakStringToLines Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/markdown.md Demonstrates how to import and use the breakStringToLines function to wrap a long string to a specified line length for console output. ```javascript import { breakStringToLines } from '../lib/markdown.js' const longText = "This is a very long line of text that should be wrapped..." const wrapped = breakStringToLines(longText, 40) console.log(wrapped) ``` -------------------------------- ### Integration Example: Formatting AI Responses Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/markdown.md Shows how breakStringToLines is used within the 'ask' command to format AI-generated answers for an 80-character terminal width. ```javascript console.log(breakStringToLines(format(answer), 80)) ``` -------------------------------- ### Internal Function: scaffoldProject Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Internal function to scaffold a new project directory structure. Currently unimplemented and will throw an error if called without the `--example` flag. ```javascript async function scaffoldProject({ framework, dir, providers, adapter }) ``` -------------------------------- ### Next.js Framework Metadata Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Configuration details for the Next.js framework, including its name, example repository, demo URL, callback path, development port, and environment file. ```javascript next: { name: "Next.js", src: "https://github.com/nextauthjs/next-auth-example", demo: "https://next-auth-example.vercel.app", path: "/api/auth", port: 3000, envFile: ".env.local" } ``` -------------------------------- ### Update Environment File with Variables Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md This example shows how to define and pass an object of environment variables to the `updateEnvFile` function. Ensure that sensitive values like `AUTH_SECRET` are kept secure. ```javascript const envVars = { AUTH_SECRET: 'random_value_here', AUTH_GITHUB_ID: 'github_client_id', AUTH_GITHUB_SECRET: 'github_client_secret' } await updateEnvFile(envVars) ``` -------------------------------- ### Express Framework Metadata Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Configuration details for the Express framework, including its name, example repository, demo URL, callback path, development port, and environment file. ```javascript express: { name: "Express", src: "https://github.com/nextauthjs/express-auth-example", demo: "https://express-auth-example.vercel.app", path: "/auth", port: 3000, envFile: ".env" } ``` -------------------------------- ### Standard OAuth Provider Environment Variables Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Examples of environment variables for standard OAuth providers like GitHub, Google, and Discord. These are used to configure client IDs and secrets. ```dotenv AUTH_GITHUB_ID="github_client_id" AUTH_GITHUB_SECRET="github_client_secret" AUTH_GOOGLE_ID="google_client_id" AUTH_GOOGLE_SECRET="google_client_secret" AUTH_DISCORD_ID="discord_client_id" AUTH_DISCORD_SECRET="discord_client_secret" ``` -------------------------------- ### Comment Added by CLI to .env File Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md An example of a comment automatically added by the `npx auth` command to environment files, providing a link for more information. ```dotenv AUTH_SECRET="..." # Added by `npx auth`. Read more: https://cli.authjs.dev ``` -------------------------------- ### Register CLI Commands with Actions Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md This example demonstrates how to connect Commander.js command definitions to their respective action handlers. Each command is registered with its corresponding action function imported from the commands module. ```javascript import { ask, init, secret, add } from './commands/index.js' program.command('ask').action(ask.action) program.command('init').action(init.action) program.command('secret').action(secret.action) program.command('add').action(add.action) ``` -------------------------------- ### Apple Private Key Format Example Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/apple-gen-secret.md Illustrates the expected format for an Apple private key (.p8, PKCS#8). The module automatically strips headers and newlines to extract the base64 content. ```plaintext -----BEGIN PRIVATE KEY----- MIGHDBIDBwECAAECEQD/////////QQ== ... base64 content ... -----END PRIVATE KEY----- ``` -------------------------------- ### Initialize Auth.js Project (Interactive) Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Run this to interactively select framework, providers, and adapters. Use `undefined` for the framework to trigger the prompt. ```javascript import { action } from './commands/init.js' // Interactive: select everything await action(undefined, {}) ``` -------------------------------- ### Initialize Auth.js Project (Specify Framework) Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md Specify the target framework (e.g., 'next') and let the command prompt for other configurations. ```javascript import { action } from './commands/init.js' // Specify framework, interactive for others await action('next', {}) ``` -------------------------------- ### Import and Use Ask Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/ask-command.md Demonstrates how to import and use the `action` function from the ask command with different options for response formatting and streaming. ```javascript import { action } from './commands/ask.js' // Ask with formatted response await action({ stream: false, raw: false }) // Ask with streaming response await action({ stream: true, raw: false }) // Ask with raw Markdown output await action({ stream: false, raw: true }) ``` -------------------------------- ### Example JwtPayload for Apple JWT Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md An example of a JWT payload object conforming to the `JwtPayload` interface. This structure is used when signing JWTs for Apple Sign-In. ```javascript { iss: "ABC123DEF", iat: 1234567890, exp: 1234567890 + (180 * 86400), aud: "https://appleid.apple.com", sub: "com.example.app.service" } ``` -------------------------------- ### Get HTTPS Proxy URL Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/is-online.md Retrieves the configured HTTPS proxy URL. It first checks environment variables (`process.env.https_proxy`) and then falls back to npm configuration (`npm config get https-proxy`). Returns undefined if no proxy is set or if the npm command fails. ```javascript function getProxy() ``` ```javascript // With proxy env var process.env.https_proxy = "http://proxy:8080" getProxy() // Returns "http://proxy:8080" // With npm config getProxy() // Reads "npm config get https-proxy" ``` -------------------------------- ### Graceful Degradation for Unknown Frameworks Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This pattern shows how to handle cases where the framework is not detected, logging a message and proceeding with default .env settings. ```javascript const framework = await detectFramework(path) if (framework === "unknown") { console.log("Framework unknown, using default .env") return } ``` -------------------------------- ### Provider Properties Structure Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Defines the structure for provider properties, including name, optional setup URL, and optional instructions. The providerId serves as the key. ```javascript providers = { [providerId]: { name: string, setupUrl: string | undefined, instructions: string | undefined }, ... } ``` -------------------------------- ### Spawn Package Manager Process Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/pkg-manager.md This snippet shows how the child process is spawned with specific environment variables and stdio inheritance. ```javascript const child = spawn(packageManager, args, { stdio: "inherit", // Show all output env: { ...process.env, ADBLOCK: "1", NODE_ENV: "development", DISABLE_OPENCOLLECTIVE: "1" } }) ``` -------------------------------- ### Typical Framework Detection Usage in CLI Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/detect.md Demonstrates a common pattern for using `detectFramework` in a CLI context to determine configuration, such as the environment file name. ```javascript import { detectFramework } from '../lib/detect.js' // Typical usage in CLI const detected = await detectFramework() const envFile = frameworks[detected]?.envFile || '.env' ``` -------------------------------- ### Auth.js CLI Usage Help Source: https://github.com/nextauthjs/cli/blob/main/README.md Displays the available commands and options for the Auth.js CLI. Use this to understand the CLI's capabilities and structure. ```sh Usage: auth [options] [command] Options: -V, --version output the version number -h, --help display help for command Commands: ask [options] Ask about docs, API, or auth concepts. init [options] [framework] Initialize a project. secret [options] Generate a random string and add it to the .env file. add [provider] Register a new authentication provider help [command] display help for command ``` -------------------------------- ### Init Command - Action Function Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/init-command.md The `action` function is the core of the init command. It takes a framework and options to scaffold a new Auth.js project. It handles interactive prompts for configuration if parameters are omitted. ```APIDOC ## Function: action ```javascript export async function action(framework, options) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | framework | string | no | undefined | The target framework name (next, express, sveltekit). If omitted, user is prompted to select. | | options.example | boolean | no | false | Clone a full working example instead of scaffolding from scratch. | ### Return Type Returns `Promise`. Side effects: creates project directory structure, initializes git repos, and modifies .env files. ### Behavior 1. **Framework Selection**: If `framework` not provided, interactive prompt shows framework choices 2. **Project Name**: Prompts user for project directory name with default `my-{framework}-app` 3. **Clone Example** (if `options.example=true`): - Clones framework example repository via git - Optionally initializes AUTH_SECRET via `secretAction()` - Runs package manager install - Logs project creation summary with source and demo URLs 4. **Provider Selection**: Checkbox prompt to select multiple OAuth providers from `meta.providers` 5. **Database Adapter**: Dropdown to select database adapter (or "none") 6. **Project Scaffolding**: Would call `scaffoldProject()` to create directory structure (currently unimplemented) ### Throws | Error | Condition | |-------|-----------| | User force closed | User cancels interactive prompts (silently ignored) | | Scaffolding not implemented | Calling without `--example` flag (not yet implemented) | | Git/npm errors | From spawned child processes (git clone, package manager) | ### Example Usage ```javascript import { action } from './commands/init.js' // Interactive: select everything await action(undefined, {}) // Specify framework, interactive for others await action('next', {}) // Clone Next.js example project await action('next', { example: true }) // Clone SvelteKit example project await action('sveltekit', { example: true }) ``` ### CLI Usage ```bash auth init auth init next auth init express auth init sveltekit --example auth init [framework] -e ``` ### Supported Frameworks - `next`: Next.js (port 3000, .env.local) - `express`: Express (port 3000, .env) - `sveltekit`: SvelteKit (port 5173, .env) ### Supported Providers Includes 90+ OAuth providers (apple, github, google, discord, twitter, linkedin, etc.). See `meta.providers` for complete list. ### Supported Adapters 20+ database adapters including Prisma, Drizzle, MongoDB, PostgreSQL, Firebase, DynamoDB, and more. ### Internal Functions #### createFromExample(framework, dir) Clones a framework example repository and optionally initializes AUTH_SECRET. ```javascript async function createFromExample(framework, dir) ``` - Uses git to clone the example repo from framework's `src` URL - Optionally prompts to initialize .env with AUTH_SECRET - Runs package manager install - Logs success message with source and demo links #### scaffoldProject(options) Currently throws "not implemented" error. When complete, will: - Create project directory - Initialize package manager - Generate environment variables for selected providers - Add framework and dependency installations ```javascript async function scaffoldProject({ framework, dir, providers, adapter }) ``` ### Source `commands/init.js:17-121` ### Notes - The scaffolding feature is not yet fully implemented - For a working project, use the `--example` flag - Example repositories are maintained separately in nextauthjs organization ``` -------------------------------- ### PackageManager Type Definition Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Union type representing supported Node.js package managers: npm, pnpm, yarn, and bun. Returned by `getPkgManager()` to determine the installation command. ```typescript type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun' ``` -------------------------------- ### Construct Environment File Path Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This snippet demonstrates how to construct the path for an environment file using node:path.join. It logs the intended file path for verification. ```javascript import { join } from "node:path" const envFile = join(cwd, path, dotEnvFile) console.log(`Would write to: ${envFile}`) ``` -------------------------------- ### Add OAuth Provider with NextAuth.js CLI Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Register new authentication providers like GitHub or Google. Running `npx auth add` without arguments initiates an interactive selection process. ```bash npx auth add github ``` ```bash npx auth add google ``` ```bash npx auth add ``` -------------------------------- ### Data Flow: 'auth add' Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Details the process for the 'auth add' command, including framework detection, user prompts, and .env file updates. ```mermaid graph TD user[user: auth add github] --> detect_framework detect_framework(requireFramework() → detect Next.js/Express/SvelteKit) --> show_instructions show_instructions(Show GitHub setup instructions) --> prompt prompt(Prompt: Client ID & Secret) --> update_env update_env(updateEnvFile({ AUTH_GITHUB_ID, AUTH_GITHUB_SECRET })) --> write_file write_file(Write to correct .env/.env.local file) ``` -------------------------------- ### Configure SvelteKit CLI Behavior Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Set up SvelteKit specific configurations for the CLI. This object defines the framework name, source, demo URL, API path, port, and environment file, noting its different default port. ```javascript { name: "SvelteKit", src: "https://github.com/nextauthjs/sveltekit-auth-example", demo: "https://sveltekit-auth-example.vercel.app", path: "/auth", port: 5173, envFile: ".env" } ``` -------------------------------- ### Provider Configuration Interface Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Defines the structure for OAuth provider configuration, including name, an optional setup URL, and optional markdown-formatted instructions. Used for managing OAuth provider details. ```typescript interface ProviderConfig { name: string setupUrl?: string instructions?: string } ``` -------------------------------- ### Ask About Docs with NextAuth.js CLI Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Query the CLI for documentation, API information, or auth concepts. Supports streaming output and raw text responses. ```bash npx auth ask ``` ```bash npx auth ask --stream ``` ```bash npx auth ask --raw ``` -------------------------------- ### Spawn Child Process and Handle Close Event Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md This snippet shows how to spawn a child process using a package manager and attach a listener for the 'close' event to handle successful completion or errors. ```javascript const child = spawn(packageManager, args, { stdio: "inherit" }) child.on("close", (code) => { if (code !== 0) { reject({ command: `${packageManager} ${args.join(" ")}` }) } else { resolve() } }) ``` -------------------------------- ### Utilize NextAuth.js Library Utilities Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Leverage utility functions for framework detection, environment file updates, and package manager identification. Import utilities from 'auth/lib/'. ```javascript import { detectFramework } from 'auth/lib/detect.js' import { updateEnvFile } from 'auth/lib/write-env.js' import { getPkgManager } from 'auth/lib/pkg-manager.js' const framework = await detectFramework() await updateEnvFile({ MY_VAR: 'value' }) const manager = getPkgManager() ``` -------------------------------- ### List Available Adapters Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/meta.md Import and access the adapters object to retrieve display names or iterate through all available adapters. This is useful for dynamic configuration or displaying adapter options. ```javascript import { adapters } from '../lib/meta.js' // Get display name console.log(adapters.prisma) // "Prisma" // All available adapters const allAdapters = Object.entries(adapters).map(([id, name]) => ({ id, name })) ``` -------------------------------- ### Output Messages: File Created Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/write-env.md Logs a message indicating that a new .env.local file has been created with the specified variable. ```javascript 📝 Created .env.local with `AUTH_SECRET`. ``` -------------------------------- ### CLI Usage for Add Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/add-command.md Shows the command-line interface commands for adding OAuth providers. This allows users to add providers directly from their terminal. ```bash auth add auth add github auth add google auth add apple auth add discord auth add twitter ``` -------------------------------- ### Importing Private Key for Signing Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This code demonstrates importing a private key using crypto.subtle.importKey. It will throw an error if the private key is not in valid PKCS#8 format, is corrupted, or uses the wrong algorithm. ```javascript const privateKey = await globalThis.crypto.subtle.importKey( "pkcs8", binaryDer.buffer, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"] ) // Throws if key is invalid ``` -------------------------------- ### NextAuth.js CLI Command Flow Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/INDEX.md Illustrates the execution path from a user command to the CLI's internal processing and library utilization. ```mermaid graph TD user[user runs: auth [command] [args] [options]] --> index index(index.js parses with Commander.js) --> command_action command_action(calls command.action(args, options)) --> lib_utils lib_utils(Command uses lib/* utilities:) subgraph lib utilities direction LR detect[Framework detection (detect.js)] write_env[ .env file updates (write-env.js)] pkg_manager[Package manager (pkg-manager.js)] meta[Metadata (meta.js)] apple[Apple JWT (apple-gen-secret.js)] format[Formatting (markdown.js)] network[Network check (is-online.js)] end lib_utils --> output output(Output to console or file) ``` -------------------------------- ### Configure Next.js CLI Behavior Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Use this configuration object to set up Next.js specific settings for the CLI. It defines the framework name, source repository, demo URL, API path, port, and environment file. ```javascript { name: "Next.js", src: "https://github.com/nextauthjs/next-auth-example", demo: "https://next-auth-example.vercel.app", path: "/api/auth", port: 3000, envFile: ".env.local" } ``` -------------------------------- ### CLI Usage for Ask Command Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/ask-command.md Shows the command-line interface commands to invoke the ask functionality with and without options. ```bash auth ask [options] auth ask --stream auth ask --raw ``` -------------------------------- ### Error Handling for Nonexistent Directory Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/detect.md Illustrates how `detectFramework` handles non-existent paths by returning 'unknown' without throwing an error. The `try...catch` block will not execute. ```javascript import { detectFramework } from '../lib/detect.js' try { const framework = await detectFramework('./nonexistent') // Returns "unknown" - no error thrown } catch (e) { // This block will never execute } ``` -------------------------------- ### Reading Private Key File Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/errors.md This snippet shows how fs.readFileSync() throws an error if the specified private key file is not found. Ensure the private key path is correct and the file exists. ```javascript const privateKey = fs .readFileSync(path.resolve(privateKeyPath), "utf8") // Throws if file not found .replace(/-----BEGIN PRIVATE KEY-----|\n|-----END PRIVATE KEY-----/g, "") ``` -------------------------------- ### Detect Framework in Current Directory Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/detect.md Use `detectFramework` to identify the authentication framework in the current working directory. It returns the framework name or 'unknown'. ```javascript import { detectFramework } from '../lib/detect.js' // Detect framework in current directory const framework = await detectFramework() if (framework !== "unknown") { console.log(`Found ${framework}`) } ``` -------------------------------- ### Apple Private Key Format Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/configuration.md Illustrates the expected format for the private key file (.p8) used for Apple Sign-In authentication. The module automatically handles PEM headers and newlines. ```text -----BEGIN PRIVATE KEY----- MIGHDBIDBwECAAECEQD/////////QQ== ... (base64 content) -----END PRIVATE KEY----- ``` -------------------------------- ### Framework Configuration Interface Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/types.md Defines the structure for framework configuration, including name, source repository, demo URL, callback path, port, and environment file name. Used for configuring framework-specific settings in the CLI. ```typescript interface FrameworkConfig { name: string src: string demo: string path: string port: number envFile: string } ``` -------------------------------- ### updateEnvFile Source: https://github.com/nextauthjs/cli/blob/main/_autodocs/api-reference/write-env.md Adds or updates key-value pairs in the appropriate .env file for the detected framework. It handles file creation, updates, and user confirmation for overwrites. ```APIDOC ## Function: updateEnvFile ### Description Adds or updates key-value pairs in the correct .env file for the detected framework. ### Parameters #### Path Parameters - **env** (Record) - Required - Object containing key-value pairs to add/update. All values must be strings. - **envPath** (string) - Optional - Relative path to project directory (will be combined with cwd). Defaults to "". - **comment** (boolean) - Optional - Whether to append a comment explaining the CLI tool added this line. Defaults to true. ### Return Type `Promise` ### Behavior 1. Detects the framework to determine the correct .env file (e.g., `.env.local`, `.env`). 2. Constructs the file path by joining the current working directory, `envPath`, and the framework's designated env file. 3. For each environment variable: - Constructs the line in `KEY="value"` format, optionally including a comment. - Reads the existing file. - If the key exists, prompts the user for confirmation before updating. - If the key does not exist, appends it to the file content. - If the file does not exist, creates a new file with the line. 4. Writes the updated content back to the disk if any changes were made. ### Throws - Any filesystem error except ENOENT (e.g., permission errors, disk full). ### Example Usage ```javascript import { updateEnvFile } from '../lib/write-env.js' // Add AUTH_SECRET to .env/.env.local await updateEnvFile({ AUTH_SECRET: 'base64_random_value' }) // Add provider credentials with comment await updateEnvFile({ AUTH_GITHUB_ID: 'client_id_value', AUTH_GITHUB_SECRET: 'client_secret_value' }) // Add multiple variables to specific project await updateEnvFile({ AUTH_SECRET: 'secret_value', AUTH_GOOGLE_ID: 'google_id', AUTH_GOOGLE_SECRET: 'google_secret' }, './my-project') // Add without comment await updateEnvFile({ AUTH_SECRET: 'secret' }, '', false) ``` ### File Path Resolution - **Next.js**: Detected by `dependencies.next` in `package.json`, uses `.env.local`. - **Express**: Detected by `dependencies.express` in `package.json`, uses `.env`. - **SvelteKit**: Detected by `devDependencies["@sveltejs/kit"]` in `package.json`, uses `.env`. - **Unknown Framework**: Falls back to `.env`. ```