Skip to main content

Using the built in OAUTH2 route (backend)


If you are using localhost as your test environment, make sure you use instead of http://localhost in your browser otherwise you may encounter problems with the cookie setting successfully.

If you want your bot to have a web dashboard, you need to implement OAUTH2 authentication. This is a way for users to log in to your bot's website using their Discord account.

In order to implement this using Sapphire's built-in OAUTH2 feature, you will need to define OAUTH2 information within the api options in the ClientOptions:

const { SapphireClient } = require('@sapphire/framework');
const { OAuth2Scopes } = require('discord.js');

const client = new SapphireClient({
api: {
auth: {
scopes: [OAuth2Scopes.Identify, OAuth2Scopes.Guilds],
cookie: 'SAPPHIRE_AUTH',
domainOverwrite: ''

The domainOverwrite option is only required for your local testing environment where you need to use the domain as mentioned above. The reason for this is that while we attempt to resolve the domain for you, as a fully qualify IPv4 address is unique in that as a domain it would resolve to 0.1 ( format).

You should either remove it when deploying to production, or make it dynamic in some way (i.e. by using environment variables or a ternary if statement)


In the code block above we specify the OAUTH2 scopes that we want. The default of the plugin is only OAuth2Scopes.Identify, which means that no guild data will be fetched. Because we are creating a settings web dashboard we do want guild data, therefore we add the Guilds OAUTH2 scope. For more information on OAUTH2 scopes see the discord developer documentation

Once you have done this, we can leverage the built-in /oauth/callback route to handle the OAUTH2 callback and retrieve the LoginData from the Discord API. The specific data we get back depends on the scopes defined in our ClientOptions - in our case, we used the identify and the guilds scope, so we'll get both LoginData.user and LoginData.guilds.

The next step is to implement the frontend part of the OAUTH2 process. This is covered on the next page.