{"id":16869,"library":"onegraph-auth","title":"OneGraph Auth Helpers","description":"The `onegraph-auth` library provides essential client-side authentication helpers for integrating web applications with a multitude of third-party services via the OneGraph platform. It streamlines the complex OAuth login and logout flows, manages session state, and securely handles token storage in the browser. The package is currently at version 4.0.2, indicating a mature and actively maintained library. Its primary differentiator is its ability to abstract away the intricacies of individual OAuth providers, offering a unified authentication experience through OneGraph's single GraphQL endpoint. This simplifies development by reducing the need to manage multiple API keys and authentication mechanisms for services like GitHub, Stripe, and others. It is specifically designed for browser environments, leveraging the global `window` object for its operations.","status":"active","version":"4.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/OneGraph/onegraph-client/tree/master/packages/onegraph-auth","tags":["javascript","typescript"],"install":[{"cmd":"npm install onegraph-auth","lang":"bash","label":"npm"},{"cmd":"yarn add onegraph-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add onegraph-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Optional dependency for simplified integration with Apollo Client, handling authentication headers automatically.","package":"onegraph-apollo-client","optional":true}],"imports":[{"note":"The library primarily uses ES Module syntax for imports. Direct CommonJS `require` might lead to issues, especially in modern build environments, though it could sometimes work with bundlers.","wrong":"const OneGraphAuth = require('onegraph-auth');","symbol":"OneGraphAuth","correct":"import OneGraphAuth from 'onegraph-auth';"},{"note":"When using TypeScript, the `OneGraphAuthOptions` interface can be imported as a named export for type-checking the constructor options. Avoid importing directly from internal `dist/types` paths.","wrong":"import { OneGraphAuthOptions } from 'onegraph-auth/dist/types';","symbol":"OneGraphAuthOptions","correct":"import OneGraphAuth, { OneGraphAuthOptions } from 'onegraph-auth';"},{"note":"While `OneGraphAuth` is the class name, the instantiated client object is often referred to as an 'auth client instance'. TypeScript users can explicitly type the instance for better tooling.","symbol":"AuthClientInstance","correct":"const auth: OneGraphAuth = new OneGraphAuth({ appId: 'YOUR_APP_ID' });"}],"quickstart":{"code":"import OneGraphAuth from 'onegraph-auth';\n\nconst APP_ID: string = process.env.NEXT_PUBLIC_ONEGRAPH_APP_ID ?? ''; // Ensure APP_ID is loaded from environment variables\n\nif (!APP_ID) {\n  console.error('OneGraph APP_ID is not configured. Please set NEXT_PUBLIC_ONEGRAPH_APP_ID.');\n} else {\n  const auth = new OneGraphAuth({\n    appId: APP_ID,\n  });\n\n  async function handleGitHubAuth() {\n    try {\n      let isLoggedIn = await auth.isLoggedIn('github');\n\n      if (!isLoggedIn) {\n        console.log('Not logged in to GitHub, initiating login...');\n        await auth.login('github');\n        isLoggedIn = await auth.isLoggedIn('github');\n      }\n\n      if (isLoggedIn) {\n        console.log('Successfully logged in to GitHub!');\n        // Example: Get auth headers for an Apollo Client or other API calls\n        const headers = auth.authHeaders();\n        console.log('Auth Headers:', headers);\n      } else {\n        console.log('GitHub login failed or user did not grant consent.');\n      }\n    } catch (error) {\n      console.error('Error during GitHub authentication:', error);\n    }\n  }\n\n  handleGitHubAuth();\n}","lang":"typescript","description":"This quickstart demonstrates how to initialize the OneGraphAuth client, check login status for GitHub, and initiate the OAuth login flow if the user is not authenticated. It also shows how to retrieve the necessary authorization headers after a successful login, suitable for use with a GraphQL client."},"warnings":[{"fix":"Ensure `OneGraphAuth` instances are only created and methods are called within a `useEffect` hook in React, or within `window.onload` in vanilla JavaScript, to guarantee a browser environment. For SSR, conditionally import or initialize the library client-side.","message":"The `onegraph-auth` library is designed exclusively for client-side (browser) environments. It relies on the global `window` object for its operations, including handling OAuth redirects and storing tokens. Attempting to use it in a Node.js or server-side rendering (SSR) context without appropriate shims or checks will result in runtime errors related to `window` being undefined.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always provide your `appId` during `OneGraphAuth` instantiation. It is recommended to load this from environment variables (e.g., `process.env.NEXT_PUBLIC_ONEGRAPH_APP_ID` in Next.js) and include a runtime check to ensure it's defined before initialization.","message":"A valid OneGraph `appId` is absolutely required for the `OneGraphAuth` client to function. This `appId` links your application to your OneGraph project and its configured services. If the `appId` is missing or incorrect, authentication flows will fail silently or with generic errors, preventing users from logging in.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Instruct users to disable popup blockers for your domain, or provide clear UI feedback if a popup is blocked (e.g., by catching the promise rejection if the browser API allows detecting it, or by observing if `isLoggedIn` doesn't change after an expected login attempt).","message":"OneGraph handles OAuth flows via popup windows or redirects. Browser popup blockers can interfere with the `auth.login('service')` method, preventing the authentication window from appearing. Users might not understand why login isn't working, leading to a poor user experience.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For Apollo Client, use a `request` handler to dynamically set context headers, as shown in the README example: `request: (operation) => operation.setContext({headers: auth.authHeaders()})`. Alternatively, use `onegraph-apollo-client` which handles this automatically.","message":"When integrating `onegraph-auth` with GraphQL clients like Apollo, it's crucial to ensure that the `authHeaders()` method is called dynamically for each request. The authentication token can change (e.g., after a user logs in or out of a new service), and static headers will quickly become stale, leading to unauthorized requests.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Use ES Module import syntax: `import OneGraphAuth from 'onegraph-auth';`. Ensure your build configuration (e.g., `tsconfig.json`'s `module` field, Webpack/Rollup config) correctly handles ES Modules.","cause":"Attempting to import `onegraph-auth` using CommonJS `require` syntax (`const OneGraphAuth = require('onegraph-auth');`) in an environment expecting ES Modules, or when a bundler fails to correctly transpile.","error":"TypeError: onegraph_auth_1.default is not a constructor"},{"fix":"Wrap `OneGraphAuth` instantiation and method calls in client-side checks. For React, use `useEffect` or dynamic imports. For frameworks like Next.js, ensure components using `onegraph-auth` are only rendered client-side or explicitly wrap in `typeof window !== 'undefined'` checks.","cause":"The `onegraph-auth` library is being initialized or used in a non-browser environment, such as a Node.js server during server-side rendering (SSR) or in a build process, where the global `window` object is not available.","error":"ReferenceError: window is not defined"},{"fix":"This is a user-side issue. Provide clear instructions to users to allow popups from your domain. In some cases, frameworks might offer ways to detect if a popup was blocked, allowing for custom error messages or fallback UI.","cause":"The browser's built-in popup blocker prevented the OAuth login window initiated by `auth.login('service')` from appearing, disrupting the authentication flow.","error":"Auth popup was blocked by the browser."},{"fix":"Verify that `auth.login('service')` has been successfully completed and that `auth.authHeaders()` is correctly used to populate the `Authorization` header for all outgoing API requests. If using Apollo Client, ensure the `request` function dynamically calls `auth.authHeaders()` for each operation.","cause":"GraphQL requests made to OneGraph are missing the `Authorization` header, or the token provided in the header is invalid or expired. This often happens if `auth.authHeaders()` is not called dynamically or if the user is not logged in.","error":"403 Forbidden: Missing authentication token"}],"ecosystem":"npm","meta_description":null}