OneGraph Auth Helpers
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.
Common errors
-
TypeError: onegraph_auth_1.default is not a constructor
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.fixUse 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. -
ReferenceError: window is not defined
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.fixWrap `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. -
Auth popup was blocked by the browser.
cause The browser's built-in popup blocker prevented the OAuth login window initiated by `auth.login('service')` from appearing, disrupting the authentication flow.fixThis 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. -
403 Forbidden: Missing authentication token
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.fixVerify 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.
Warnings
- gotcha 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.
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install onegraph-auth -
yarn add onegraph-auth -
pnpm add onegraph-auth
Imports
- OneGraphAuth
const OneGraphAuth = require('onegraph-auth');import OneGraphAuth from 'onegraph-auth';
- OneGraphAuthOptions
import { OneGraphAuthOptions } from 'onegraph-auth/dist/types';import OneGraphAuth, { OneGraphAuthOptions } from 'onegraph-auth'; - AuthClientInstance
const auth: OneGraphAuth = new OneGraphAuth({ appId: 'YOUR_APP_ID' });
Quickstart
import OneGraphAuth from 'onegraph-auth';
const APP_ID: string = process.env.NEXT_PUBLIC_ONEGRAPH_APP_ID ?? ''; // Ensure APP_ID is loaded from environment variables
if (!APP_ID) {
console.error('OneGraph APP_ID is not configured. Please set NEXT_PUBLIC_ONEGRAPH_APP_ID.');
} else {
const auth = new OneGraphAuth({
appId: APP_ID,
});
async function handleGitHubAuth() {
try {
let isLoggedIn = await auth.isLoggedIn('github');
if (!isLoggedIn) {
console.log('Not logged in to GitHub, initiating login...');
await auth.login('github');
isLoggedIn = await auth.isLoggedIn('github');
}
if (isLoggedIn) {
console.log('Successfully logged in to GitHub!');
// Example: Get auth headers for an Apollo Client or other API calls
const headers = auth.authHeaders();
console.log('Auth Headers:', headers);
} else {
console.log('GitHub login failed or user did not grant consent.');
}
} catch (error) {
console.error('Error during GitHub authentication:', error);
}
}
handleGitHubAuth();
}