The SDK supports OAuth 2.0. Before starting, ensure OAuth2 is enabled in your Twitter App settings and the app type is set to either a 'confidential client' or a 'public client'.
Creating a Public Auth Client
Use this for client-side or public applications where the client_secret cannot be kept secure.
Creating a Confidential Auth Client
Use this for server-side applications where you can securely store the client_secret.
OAuth 2.0 Workflow
- Generate Auth URL: Use
authClient.generateAuthURL with a code_challenge_method (e.g., s256). - Redirect User: Send the user to the generated URL.
- Request Access Token: After the user approves, capture the
code from the callback URL and call authClient.requestAccessToken(code). - Revoke Token: Use
authClient.revokeAccessToken() to invalidate the token.
// Public Client Example
const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID,
callback: "http://127.0.0.1:3000/callback",
scopes: ["tweet.read", "users.read", "offline.access"],
});
const client = new Client(authClient);
// Generating the URL
const authUrl = authClient.generateAuthURL({
code_challenge_method: "s256",
});
// Requesting token after callback
await authClient.requestAccessToken(code);