Files
YouTube.js/examples/auth/README.md
Luan abd8a82cd0 chore(docs): Update auth documentation and examples (#568)
* chore(docs): Update auth documentation and examples

* chore(docs): Minor rewording

* chore(docs): Fix library version in the OAuth2 example
2024-01-08 20:16:16 -03:00

2.3 KiB

OAuth2

Custom OAuth2 Credentials

Just like the official Data API, YouTube.js supports using your own OAuth2 credentials. A working example can be found here.

YouTube TV OAuth2

The library supports signing in using YouTube TV's client id. This is the recommended way to sign in as it doesn't require you to create your own OAuth2 credentials.

// 'auth-pending' is fired with the info needed to sign in via OAuth.
yt.session.on('auth-pending', (data) => {
    // data.verification_url contains the URL to visit to authenticate.
    // data.user_code contains the code to enter on the website.
});

// 'auth' is fired once the authentication is complete
yt.session.on('auth', ({ credentials }) => {
  // do something with the credentials, eg; save them in a database.
  console.log('Sign in successful');
});

// 'update-credentials' is fired when the access token expires, if you do not save the updated credentials any subsequent request will fail 
yt.session.on('update-credentials', ({ credentials }) => {
  // do something with the updated credentials
});
  
await yt.session.signIn(/* credentials */);

A working example can be found here.

Cache Credentials

If you don't want to start the sign in flow every time you initialize the session, you can cache the credentials. Note that this SHOULD NOT be used in production, save your credentials in a database/file instead and pass them to Session#signIn(creds?) when signing in.

// If you use this, the next call to signIn won't fire 'auth-pending' instead just 'auth'
await yt.session.oauth.cacheCredentials();

Note: When using cached credentials, you are still required to make a call to Session#signIn().

Sign Out

The sign out method may be used to sign out of the current session. This removes and revokes the credentials.

await yt.session.signOut();

// if you don't want to sign out of the current session
// and only want to delete the cached credentials, use:
await yt.session.oauth.removeCache();

Cookies

Note

This is not as reliable as OAuth2 as cookies expire and can be completely revoked at any time.

const yt = await Innertube.create({
  cookie: '...'
});