Add X (Twitter) Sign-In to Your App

Enable "Sign in with X" for your application's users through OAuth42's social authentication feature.

What You'll Build

In this tutorial, you'll configure X (formerly Twitter) as a social identity provider for your OAuth42 application. Your users will be able to click "Sign in with X" and authenticate using their X account.

How it works:

  • User clicks "Sign in with X" in your app
  • OAuth42 redirects to X for authentication
  • X authenticates the user and returns to OAuth42
  • OAuth42 creates/links the user account and issues tokens to your app
  • Your app receives the tokens and the user is logged in

Note about email: X does not provide user email addresses through its standard OAuth flow. Users who sign in with X will have a placeholder email generated ([email protected]). They can update their email in their profile settings after signing up.

Prerequisites

Step 1: Create X Developer App

  1. Go to the X Developer Portal - Projects & Apps
  2. Click Create Project or select an existing project
  3. Give your project a name and description
  4. Select your use case (e.g., "Building tools for X users")
  5. Create a new app within the project or use an existing one
  6. Click the gear icon next to your app in the project list to open Settings

X Developer Account Required: If you don't have an X Developer account, you'll need to apply at developer.x.com. Basic access (free) is sufficient for OAuth 2.0 user authentication.

Step 2: Configure OAuth 2.0 Settings

  1. In your app settings, scroll to User authentication settings
  2. Click Set up or Edit
  3. Enable OAuth 2.0
  4. Set App permissions (required):
    • Read - Select this option (reads posts and profile information)
    • "Read and write" is only needed if your app will post on behalf of users
  5. Set Type of App (required):
    • Select Web App, Automated App or Bot (Confidential client)
    • This is correct for OAuth42 since client secrets are stored securely server-side
    • Do NOT select "Native App" - that's for mobile apps that can't store secrets
  6. Configure the Callback URI / Redirect URL (see below)
  7. Configure the Website URL to your app's URL
  8. Click Save

About "Request email from users": You can optionally enable this toggle if you provide privacy policy and terms of service URLs. However, even with this enabled, X does not guarantee that email addresses will be provided - many users have this data private. OAuth42 handles this gracefully by generating placeholder emails.

Step 3: Configure Redirect URLs

In the X Developer Portal, add the OAuth42 callback URL as a Redirect URI:

Callback URI / Redirect URL

This is where X will redirect after authentication. OAuth42 handles this automatically:

Production:

https://api.oauth42.com/api/social-auth/callback

Local Development:

https://localhost:8443/api/social-auth/callback

Tip: Add both production and local development URLs so you can test locally and in production.

Step 4: Get Client Credentials

  1. In your X app settings, go to Keys and tokens
  2. Under OAuth 2.0 Client ID and Client Secret, you'll find:
    • Client ID - Copy this value
    • Client Secret - Click to reveal and copy (you may need to regenerate if you haven't saved it)

Keep your Client Secret safe! Never expose it in frontend code or commit it to version control.

Step 5: Configure X in OAuth42 Portal

Now configure X as a social provider in your OAuth42 application:

  1. Log in to the OAuth42 Portal
  2. Navigate to Applications and select your application
  3. Click the Social Providers tab
  4. Click Add Provider
  5. Select Twitter from the dropdown (this is X)
  6. Enter the Client ID you copied from X Developer Portal
  7. Enter the Client Secret you copied from X Developer Portal
  8. Click Add Provider to save

Secure Storage: Your X Client Secret is automatically encrypted with AES-256 before being stored. It's never logged or exposed in plain text.

Step 6: Add X Sign-In Button to Your App

If you're using OAuth42's hosted auth pages, the X Sign-In button appears automatically when you enable the provider. No code changes needed!

For custom login pages, add an X Sign-In button that initiates the social auth flow:

"use client"

import { useState } from 'react'

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)

  const handleXSignIn = async () => {
    setIsLoading(true)

    // Call OAuth42's social auth init endpoint
    const response = await fetch('/api/auth/social/twitter', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'twitter',
        client_id: process.env.NEXT_PUBLIC_OAUTH42_CLIENT_ID,
        is_signup: true, // Allow account creation
      }),
    })

    const data = await response.json()

    if (data.authorization_url) {
      // Redirect to X
      window.location.href = data.authorization_url
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="max-w-md w-full space-y-6 p-8 bg-white rounded-lg shadow">
        <h1 className="text-2xl font-bold text-center">Sign In</h1>

        <button
          onClick={handleXSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-3 py-3 px-4 bg-black text-white rounded-lg hover:bg-gray-900 transition-colors"
        >
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
          </svg>
          {isLoading ? 'Redirecting...' : 'Continue with X'}
        </button>

        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-gray-300" />
          </div>
          <div className="relative flex justify-center text-sm">
            <span className="px-2 bg-white text-gray-500">or</span>
          </div>
        </div>

        {/* Your regular email/password login form */}
        <form className="space-y-4">
          <input
            type="email"
            placeholder="Email"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <input
            type="password"
            placeholder="Password"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <button
            type="submit"
            className="w-full py-3 px-4 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            Sign In
          </button>
        </form>
      </div>
    </div>
  )
}

Step 7: Create API Route for Social Auth (Custom Login Only)

If using a custom login page, create an API route to initiate the social auth flow:

mkdir -p app/api/auth/social/twitter
touch app/api/auth/social/twitter/route.ts

Add the following code to app/api/auth/social/twitter/route.ts:

import { NextRequest, NextResponse } from 'next/server'

const API_BASE_URL = process.env.OAUTH42_ISSUER || 'https://api.oauth42.com'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    const response = await fetch(`${API_BASE_URL}/api/social-auth/init`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'twitter',
        client_id: body.client_id,
        is_signup: body.is_signup || true, // Usually allow signup for X users
        state: body.state,
      }),
    })

    const data = await response.json()

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status })
    }

    return NextResponse.json(data)
  } catch (error) {
    console.error('[Social Auth] Error:', error)
    return NextResponse.json(
      { error: 'Failed to initiate social auth' },
      { status: 500 }
    )
  }
}

Using Hosted Auth? Skip this step! OAuth42's hosted auth pages automatically include the X Sign-In button when you enable the provider.

Step 8: Test X Sign-In

  1. Start your application
  2. Navigate to your login page
  3. Click "Continue with X"
  4. You'll be redirected to X's authorization page
  5. Authorize the application with your X account
  6. X redirects back to OAuth42
  7. OAuth42 creates/links your user and redirects to your app
  8. You're now logged in!

Success! Your users can now sign in with their X accounts.

How Account Linking Works

Since X doesn't provide email addresses, account linking works differently:

New User (Signup)

A new user account is created with their X profile info (name, username, profile picture) and a placeholder email. The user can update their email later.

Existing X User (Login)

If the X account ID is already linked to a user, they're logged into that existing account.

Multiple Social Providers

Users can link multiple social providers (Google, Apple, X) to the same account, giving them flexibility in how they sign in.

Security Considerations

  • PKCE: OAuth42 uses PKCE (Proof Key for Code Exchange) for all X auth flows, preventing authorization code interception attacks
  • State Parameter: CSRF protection via cryptographically random state tokens
  • Encrypted Storage: X client secrets are encrypted at rest using AES-256
  • Basic Auth: X requires client credentials via Basic Authentication header for token exchange
  • No Email: X doesn't provide email - users get placeholder emails and should be prompted to add a real email

Troubleshooting

"Callback URL mismatch" error

The callback URL in X Developer Portal doesn't match. Make sure you've added the exact OAuth42 callback URL: https://api.oauth42.com/api/social-auth/callback

"Twitter social login not configured" error

The X OAuth credentials are not configured for this application. Go to the OAuth42 Portal → Applications → Your App → Social Providers tab and verify that Twitter (X) is configured with valid credentials.

"Failed to authenticate with X" error

This usually means the Client ID or Client Secret is incorrect. Double-check your credentials in both X Developer Portal and OAuth42 Portal.

"User has placeholder email"

This is expected! X doesn't provide email addresses. Consider prompting users to add their email after signing up, or use their X username for identification.

Next Steps

Need Help?

Having trouble with X Sign-In? Check our documentation or reach out to support.