Remix Auth Twitter Strategy

4.0.0 · active · verified Wed Apr 22

remix-auth-twitter is an authentication plugin for Remix applications, specifically designed to integrate with the `remix-auth` library. It provides strategies for authenticating users via Twitter's (now X's) OAuth protocols, supporting both the older OAuth 1.0a (via `Twitter1Strategy`) and the newer OAuth 2.0 (via `Twitter2Strategy`). The current stable version is 4.0.0, which aligns with and requires `remix-auth@4`. Releases are primarily driven by compatibility updates with `remix-auth` major versions and changes to the Twitter API (e.g., domain changes from `twitter.com` to `x.com`). A key differentiator is its dual support for both OAuth versions and direct integration into the Remix ecosystem, abstracting much of the OAuth flow complexity.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the `Twitter2Strategy` (OAuth 2.0) with `remix-auth`, handle environment variables for credentials, and process the authentication callback to retrieve user information using an external Twitter API client.

import { Authenticator } from "remix-auth";
import { Twitter2Strategy } from "remix-auth-twitter";
import TwitterApi from "twitter-api-v2"; // Example external library for Twitter API calls

interface User { /* Define your user type */ id: string; username: string; accessToken: string; }

export let authenticator = new Authenticator<User>();

const clientID = process.env.TWITTER_CLIENT_ID ?? '';
const clientSecret = process.env.TWITTER_CLIENT_SECRET ?? '';

if (!clientID || !clientSecret) {
  throw new Error(
    "TWITTER_CLIENT_ID and TWITTER_CLIENT_SECRET must be provided"
  );
}

authenticator.use(
  new Twitter2Strategy(
    {
      clientID,
      clientSecret,
      callbackURL: "https://my-app/login/callback",
      scopes: ["users.read", "tweet.read", "tweet.write"],
    },
    async ({ request, tokens }) => {
      const accessToken = tokens.accessToken();

      // In this example, we use an external library to get user profile details
      const userClient = new TwitterApi(accessToken);
      const result = await userClient.v2.me({
        "user.fields": ["profile_image_url"],
      });
      // Consider robust error handling for API calls
      const { id, username } = result.data;

      // This is a placeholder for your actual user registration/lookup logic
      async function registerUser(token: string, userId: string, uname: string): Promise<User> {
        // In a real app, you would save/retrieve user data from a database
        console.log(`User authenticated: ${uname} (ID: ${userId})`);
        return { id: userId, username: uname, accessToken: token };
      }
      return await registerUser(accessToken, id, username);
    }
  )
);

// Example route action to initiate login
/*
export async function action({ request }: ActionFunctionArgs) {
  return authenticator.authenticate("twitter2", request, {
    successRedirect: "/dashboard",
    failureRedirect: "/login",
  });
}

// Example callback route loader
export async function loader({ request }: LoaderFunctionArgs) {
  return authenticator.authenticate("twitter2", request, {
    successRedirect: "/dashboard",
    failureRedirect: "/login",
  });
}
*/

view raw JSON →