Better Auth Instagram Provider
The `better-auth-instagram` package provides an Instagram OAuth provider specifically designed to integrate with the `better-auth` authentication framework. Currently at version 0.0.7, it functions as a plugin, allowing developers to easily add 'Login with Instagram' functionality to their TypeScript applications. It leverages `@better-fetch/fetch` for making robust API requests and `zod` for schema validation, aligning with the `better-auth` ecosystem's focus on type-safety and developer experience. While `better-auth` (currently at 1.4.0) offers a comprehensive, framework-agnostic authentication solution with a plugin-based architecture, `better-auth-instagram` simplifies the complexities of Instagram's OAuth flow, requiring proper setup of an Instagram Business Login API application. Its release cadence is tied to the `better-auth` ecosystem, focusing on incremental improvements and compatibility. Key differentiators include its tight integration with `better-auth`'s plugin system and built-in type safety with Zod.
Common errors
-
Error: invalid_grant - The authorization code has expired or been revoked.
cause The authorization code exchanged during the OAuth flow is single-use and short-lived. This error often indicates a race condition, a double-submission, or a delay in processing.fixEnsure that the callback handler processes the authorization code promptly and only once. Check server logs for any repeated attempts or slow responses during the code exchange phase. Verify server time synchronization. -
redirect_uri_mismatch: The redirect URI in the request does not match the ones authorized for the client application.
cause The `redirect_uri` parameter sent in the OAuth authorization request does not exactly match one of the 'Valid OAuth Redirect URIs' configured in your Instagram Developer App.fixGo to your Instagram Developer App settings. Under 'Instagram Basic Display' or 'Instagram Business Login' (depending on your setup), navigate to 'Client OAuth Settings' and ensure the `http://localhost:3000/api/auth/oauth2/callback/instagram` (or your production URL) is added and exactly matches the URI used in your `better-auth` configuration. -
Error: User canceled authentication or denied permissions.
cause The user explicitly declined the authentication request or revoked permissions during the Instagram OAuth process.fixThis is expected user behavior. Handle this gracefully in your client-side application, perhaps by redirecting them back to a login page or displaying a message indicating that Instagram login was canceled. -
ZodError: Invalid input
cause Input data (e.g., API response, profile data) failed schema validation defined by Zod within the package or your custom configurations.fixInspect the detailed error message for the specific field that failed validation. This might indicate an unexpected API response format from Instagram or a mismatch in your `instagramConfig` or data processing logic. If it's an upstream API change, an update to `better-auth-instagram` might be needed.
Warnings
- breaking The Instagram Basic Display API reached End-of-Life on December 4, 2024. While `better-auth-instagram` is designed to work with the Instagram Business Login API, users *must* ensure their Instagram app is correctly configured for the Business Login API and not the deprecated Basic Display API. Failure to do so will result in authentication failures.
- gotcha As a pre-release version (0.0.7), the package's API surface or internal behavior might change without adhering to strict semantic versioning, potentially leading to breaking changes between minor or patch versions.
- gotcha Instagram applications must be properly configured, including adding the 'Instagram product', setting up 'Instagram business login', and accepting 'Tester Invites' if the app is not live. Failing to do so will prevent login for non-tester accounts.
- gotcha By default, `better-auth` and its plugins like `better-auth-instagram` do not automatically update user profile data (e.g., username, profile picture) upon account linking or subsequent logins. This requires manual implementation using database hooks.
- gotcha Environment variables for `INSTAGRAM_APP_ID` and `INSTAGRAM_APP_SECRET` must be set correctly. Incorrect or missing values will lead to failed OAuth flows.
Install
-
npm install better-auth-instagram -
yarn add better-auth-instagram -
pnpm add better-auth-instagram
Imports
- instagram
const { instagram } = require('better-auth-instagram');import { instagram } from 'better-auth-instagram'; - instagramConfig
import instagramConfig from 'better-auth-instagram/config';
import { instagramConfig } from 'better-auth-instagram'; - betterAuth
import betterAuth from 'better-auth';
import { betterAuth } from 'better-auth';
Quickstart
import { betterAuth } from 'better-auth';
import { instagram } from 'better-auth-instagram';
import { createAuthClient } from 'better-auth/client';
import { genericOAuthClient } from 'better-auth/client/plugins';
// Server-side Better Auth instance configuration
export const auth = betterAuth({
plugins: [
instagram(), // Adds the Instagram OAuth provider
],
// ... other better-auth configurations like database, secret, etc.
});
// Client-side Better Auth client instance configuration
// This should typically be in a separate client-side file
export const authClient = createAuthClient({
plugins: [
genericOAuthClient() // Required for OAuth client-side flows
]
});
// Example of initiating the sign-in flow on the client-side
async function signInWithInstagram() {
if (typeof window !== 'undefined') {
console.log('Initiating Instagram sign-in...');
await authClient.signIn.oauth2({
providerId: 'instagram',
callbackURL: '/dashboard', // URL to redirect to after successful auth
errorCallbackURL: '/login?error=instagram_failed'
});
}
}
// Call this function from a UI element, e.g., a button click
signInWithInstagram();
// In your .env file:
// INSTAGRAM_APP_ID="your_instagram_app_id"
// INSTAGRAM_APP_SECRET="your_instagram_app_secret"
// BETTER_AUTH_SECRET="super_secret_key_at_least_32_chars"
// BETTER_AUTH_URL="http://localhost:3000" // Base URL of your app for callbacks