{"id":16819,"library":"google-auto-auth","title":"Google Auto Authentication","description":"google-auto-auth is a JavaScript library designed to simplify the process of authenticating requests to Google APIs. It abstracts away much of the complexity of managing credentials and obtaining access tokens, leveraging Google's Application Default Credentials (ADC) strategy to automatically find credentials based on the application's environment. This means it can seamlessly authenticate on Google Cloud Platform, when authenticated with the `gcloud` SDK, or via the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. For environments where automatic authentication isn't available, it supports explicit configuration using key files or credentials objects. The current stable version is `0.10.1`. While not on a rapid release cycle, it is actively maintained as a utility for streamlined Google API access, providing a thin layer over the `google-auth-library` to offer a more developer-friendly interface for common authentication patterns.","status":"active","version":"0.10.1","language":"javascript","source_language":"en","source_url":"https://github.com/stephenplusplus/google-auto-auth","tags":["javascript","google","authentication","jwt","service","account","googleapis","gcloud","cloud"],"install":[{"cmd":"npm install google-auto-auth","lang":"bash","label":"npm"},{"cmd":"yarn add google-auto-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add google-auto-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This is the underlying official Google authentication library that `google-auto-auth` uses to perform the actual credential management and token acquisition.","package":"google-auth-library"}],"imports":[{"note":"This library is primarily CommonJS (`require`). While ESM interop might work in some bundlers, `require` is the intended and most reliable import mechanism.","wrong":"import googleAutoAuth from 'google-auto-auth';","symbol":"googleAutoAuth","correct":"const googleAutoAuth = require('google-auto-auth');"},{"note":"Since v0.7.0, the `new` keyword is explicitly forbidden for instantiating the client. The function should be invoked directly. Using `new` will result in a runtime error.","wrong":"const authClient = new googleAutoAuth(authConfig);","symbol":"AuthClient","correct":"const authClient = googleAutoAuth(authConfig);"},{"note":"The `authorizeRequest` method is available on the *instance* returned by `googleAutoAuth()`, not on the module itself.","wrong":"googleAutoAuth.authorizeRequest(reqOpts, callback);","symbol":"authorizeRequest","correct":"authClient.authorizeRequest(reqOpts, callback);"}],"quickstart":{"code":"const googleAutoAuth = require('google-auto-auth');\nconst path = require('path');\n\n// IMPORTANT: In a real application, never hardcode credentials or paths directly.\n// Use environment variables or a secure configuration management system.\n// For demonstration, we'll simulate a key file path.\nprocess.env.GOOGLE_APPLICATION_CREDENTIALS = process.env.GOOGLE_APPLICATION_CREDENTIALS ?? path.join(__dirname, 'mock-key.json');\n\n// If GOOGLE_APPLICATION_CREDENTIALS is not set or not valid, you must provide authConfig.\n// Example with explicit credentials (replace with your actual data):\nconst authConfig = {\n  // keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS, // Path to a .json, .pem, or .p12 key file\n  // OR\n  // credentials: {\n  //   client_email: process.env.GOOGLE_CLIENT_EMAIL ?? 'your-service-account@your-project.iam.gserviceaccount.com',\n  //   private_key: process.env.GOOGLE_PRIVATE_KEY ?? '-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n',\n  // },\n  scopes: ['https://www.googleapis.com/auth/cloud-platform'] // Required scopes for your API requests\n};\n\n// Create an auth client. It will automatically attempt to find credentials.\n// If authConfig is empty and no default credentials are found, it might fail.\nconst auth = googleAutoAuth(authConfig);\n\n// 1. Authorize an HTTP request object\nauth.authorizeRequest({\n  method: 'GET',\n  uri: 'https://storage.googleapis.com/storage/v1/b'\n}, (err, authorizedReqOpts) => {\n  if (err) {\n    console.error('Error authorizing request:', err.message);\n    // Handle specific errors like MISSING_SCOPE\n    if (err.code === 'MISSING_SCOPE') {\n      console.error('Missing required scopes. Please configure `authConfig.scopes`.');\n    }\n    return;\n  }\n  console.log('Authorized Request Options:', authorizedReqOpts);\n  // authorizedReqOpts now contains `headers: { Authorization: 'Bearer {{token}}' }`\n});\n\n// 2. Get an access token directly\nauth.getToken((err, token) => {\n  if (err) {\n    console.error('Error getting token:', err.message);\n    return;\n  }\n  console.log('Access Token:', token ? token.substring(0, 20) + '...' : 'No token received');\n});\n\n// 3. Get the underlying google-auth-library client\nauth.getAuthClient((err, client) => {\n  if (err) {\n    console.error('Error getting auth client:', err.message);\n    return;\n  }\n  console.log('Underlying google-auth-library client type:', client.constructor.name);\n  // You can interact with the google-auth-library client directly here if needed.\n});\n","lang":"javascript","description":"This quickstart demonstrates how to initialize `google-auto-auth`, authorize an example API request, directly retrieve an access token, and access the underlying `google-auth-library` client. It highlights credential auto-discovery and explicit configuration."},"warnings":[{"fix":"Remove `new` from client instantiation: `const auth = googleAutoAuth(config);`","message":"The `new` keyword is no longer supported when instantiating the `google-auto-auth` client. Direct invocation of the function (`googleAutoAuth({...})`) is now required.","severity":"breaking","affected_versions":">=0.7.0"},{"fix":"Upgrade your Node.js runtime to version 4.0.0 or later.","message":"Node.js version 4 or higher is now a strict requirement. Environments running older Node.js versions will not be supported.","severity":"breaking","affected_versions":">=0.7.0"},{"fix":"Ensure `authConfig.scopes` contains all required scope URLs for your target Google API. Consult the API's documentation for exact scope requirements.","message":"When `authorizeRequest` returns an error with `err.code = 'MISSING_SCOPE'`, it means the configured `authConfig.scopes` array does not include the necessary OAuth 2.0 scopes for the API you are trying to access.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Verify your environment setup or explicitly provide `authConfig.keyFilename` or `authConfig.credentials` when initializing `googleAutoAuth`.","message":"Automatic authentication relies on specific environmental conditions: running on Google Cloud Platform, being authenticated with the `gcloud` SDK, or having `GOOGLE_APPLICATION_CREDENTIALS` environment variable set to a valid JSON key file path. If these conditions are not met, explicit `authConfig` is required.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Use environment variables (e.g., `GOOGLE_APPLICATION_CREDENTIALS`), a secure secret manager (like Google Secret Manager), or rely on Application Default Credentials for production environments.","message":"Never embed service account private keys or full key file content directly in your source code, especially for public repositories. These are sensitive credentials.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Remove the `new` keyword. Instead of `new googleAutoAuth()`, use `googleAutoAuth()`.","cause":"Attempting to use the `new` keyword to instantiate the `google-auto-auth` client after v0.7.0.","error":"TypeError: googleAutoAuth is not a constructor"},{"fix":"Ensure you are running on GCP, logged in via `gcloud auth application-default login`, or set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a valid service account key file path. Alternatively, provide credentials explicitly in `authConfig`.","cause":"The library failed to automatically find credentials in the environment (e.g., not on GCP, `gcloud` not authenticated, `GOOGLE_APPLICATION_CREDENTIALS` not set or invalid).","error":"Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started to authenticate."},{"fix":"Review the documentation for the Google API you are calling and add the necessary scope URLs (e.g., `https://www.googleapis.com/auth/cloud-platform`) to the `scopes` array in your `authConfig`.","cause":"The API request requires specific OAuth scopes that were not provided in the `authConfig.scopes` array.","error":"Error: MISSING_SCOPE"}],"ecosystem":"npm","meta_description":null}