8
Fullstack

Auth Social (OAuth)

A secure, full-stack OAuth authentication component with GitHub integration, server actions, and seamless user management for Next.js applications.

Social OAuth Authentication

A comprehensive OAuth authentication component that provides secure GitHub integration with beautiful UI, automatic user management, and seamless Next.js server actions integration. Features real-time feedback, secure token handling, and production-ready OAuth flow implementation.

Social OAuth Authentication Component
Loading component registry...

Installation

Install the component using the AxionsJS CLI:

npx axionjs-ui add social-auth

Configure your environment variables in .env:

# Database
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"

# OAuth Configuration
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"

# Authentication
AUTH_SECRET="your-auth-secret"
NEXT_PUBLIC_APP_URL="http://localhost:3000"

# Email (Optional)
EMAIL_SERVER_HOST="smtp.gmail.com"
EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER="your-email@gmail.com"
EMAIL_SERVER_PASSWORD="your-app-password"
EMAIL_FROM="Your App <your-email@gmail.com>"

Set up GitHub OAuth App in your GitHub Settings:

  • Go to Settings → Developer settings → OAuth Apps
  • Create new OAuth App
  • Set Authorization callback URL to: http://localhost:3000/api/auth/callback/github

Set up Prisma schema and push to database:

npx prisma db push

The component includes complete database models for users and OAuth accounts. Server actions and OAuth utilities are pre-configured and ready to use.

Database Schema

Add the following models to your schema.prisma file:

schema.prisma
model User {
  id                    String                 @id @unique @default(cuid())
  name                  String?
  email                 String?                @unique
  image                 String?
  password              String?
  isTwoFactorEnabled    Boolean                @default(false)
  emailVerified         DateTime?
  twoFactorConfirmation TwoFactorConfirmation?
  accounts              Account[]
 
  @@map("users")
}
 
model Account {
  id                String  @id @default(cuid())
  userId            String  @map("user_id")
  type              String
  provider          String
  providerAccountId String  @map("provider_account_id")
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?
 
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
 
  @@unique([provider, providerAccountId])
  @@map("accounts")
}

Run npx prisma db push after adding the schema to apply changes to your database.

Usage

Import and use the OAuthLogin component:

app/auth/login/page.tsx
"use client";
import { OAuthLogin } from "@/components/oauth-login";
 
export default function LoginPage() {
  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="mx-auto max-w-xl px-4">
        <OAuthLogin
          onSuccess={(provider, user) => {
            console.log("OAuth Success:", { provider, user });
            // Redirect to dashboard or handle success
          }}
          onError={(error) => {
            console.error("OAuth Error:", error);
            // Handle error state
          }}
          providers={["github"]}
        />
      </div>
    </div>
  );
}

Component Props

PropTypeDefault
onSuccess
(provider: string, user: any) => void
undefined
onError
(error: string) => void
undefined
title
string
"Welcome"
description
string
"Sign in to your account to continue"
className
string
""
redirectUrl
string
undefined
providers
"github"[]
["github"]

Server Actions

The component utilizes Next.js server actions for secure OAuth operations:

actions/oauth-actions.ts
export const initiateOAuthLogin = async (
  provider: "github",
  redirectUrl?: string,
): Promise<OAuthActionResult> => {
  try {
    if (!["github"].includes(provider)) {
      return { error: "Unsupported OAuth provider" };
    }
 
    const clientId = process.env[`${provider.toUpperCase()}_CLIENT_ID`];
    if (!clientId) {
      return { error: `${provider} OAuth is not configured` };
    }
 
    const authUrl = generateOAuthUrl(provider, redirectUrl);
 
    return {
      success: "Redirecting to OAuth provider",
      redirectUrl: authUrl,
    };
  } catch (error) {
    console.error("OAuth initiation error:", error);
    return { error: "Failed to initiate OAuth login" };
  }
};

Features:

  • Provider validation and configuration checking
  • Secure URL generation with CSRF protection
  • Comprehensive error handling
  • Environment variable validation

Key Features

OAuth Utilities

The component includes utility functions for OAuth URL generation:

oauth-utils.ts
export const generateOAuthUrl = (
  provider: string,
  redirectUrl?: string,
): string => {
  const baseUrls = {
    github: "https://github.com/login/oauth/authorize",
  };
 
  const params = new URLSearchParams({
    client_id: process.env[`${provider.toUpperCase()}_CLIENT_ID`] || "",
    redirect_uri:
      redirectUrl ||
      `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback/${provider}`,
    scope: "user:email",
    response_type: "code",
    state: crypto.randomUUID(), // CSRF protection
  });
 
  return `${baseUrls[provider as keyof typeof baseUrls]}?${params.toString()}`;
};

Utility Features:

  • Secure URL generation with proper encoding
  • CSRF protection with random state parameter
  • Configurable redirect URLs
  • Environment-based configuration

The OAuth utilities automatically handle scope configuration and security parameters for each provider.

Security Features

The Social Auth component implements multiple security layers:

  • CSRF Protection: Random state parameter prevents cross-site request forgery
  • Environment Validation: Checks for required OAuth credentials
  • Secure Token Exchange: Direct server-to-server communication with OAuth providers
  • Account Linking: Prevents duplicate accounts and manages user relationships
  • Input Validation: Validates all OAuth responses and user data
  • Error Handling: Secure error messages that don’t leak sensitive information

Always use HTTPS in production and keep your OAuth client secrets secure. Never expose client secrets in client-side code.

Conclusion

The Social Auth component provides a complete, production-ready solution for adding OAuth authentication to your Next.js applications. With GitHub integration, comprehensive security features, and seamless server actions integration, it delivers both excellent user experience and robust authentication capabilities.

On this page