Skip to main content

Discord

Register your app in Discord's Developer Dashboard

To use the Discord Provider you will need a client id and a client secret. You will get them while following the process to setup Discord OAuth 2.0 for your application. Follow the instructions in the following link:

info

When asked for an origin URL, insert the origin of the url in which your app is hosted.

Examples:

  • http://localhost:3000
  • https://www.example.com

When asked for a redirect URL (or callback), insert[http or https]://[origin]/[your route for Discord authentication]

Examples:

  • http://localhost:8000/auth/discord
  • https://www.example.com/api/login/discord
  • https://www.example.com/godel/russell/myDiscordLogin

Discord's official guide (Follow the guide until you get a client id and client secret and setup a callback. Don't worry about the rest, Gatekeeper will take care of that): https://discord.com/developers/docs/topics/oauth2/#shared-resources

Discord Provider

Options

Option nameDescriptionDefault valueRequired?
clientIdYour Discord OAuth client idYes
clientSecretYour Discord OAuth client secretYes
callbackURLThe URL that will serve as callback for Discord OAuthYes
scopeThe OAuth scopes that will be granted to the access token['identify', 'email']No
danger

To the callbackURL option you must provide the URL you provided when asked for a redirect (or callback) URL when registering your Discord OAuth app.

Handler

The Discord Provider passes three parameters to the handler:

  • refresh_token: The OAuth refres token. It is usually only given the first time a user signs-in to your application
  • access_token: The OAuth access token.
  • profile: The information of the Discord user.

Errors

The predefined errors of this provider are:

  • UserNotFound

Examples

Example #1

Create a Discord Provider

import gatekeeper from 'gatekeeper-authentication'
import { DiscordProvider } from 'gatekeeper-authentication/providers/discord'

const DiscordAuth = new DiscordProvider({
clientId: '<YOUR DISCORD CLIENT ID>',
clientSecret: '<YOUR DISCORD CLIENT SECRET>',
callbackURL: 'https://yourdomainorlocalhost.com/auth/discord'
}, function handler(refresh_token, access_token, profile) => {
const user = User.findOne({ discordId: profile.sub })

if (user == null) {
// For example, if the user does not exist, create it
User.create({
username: profile.name,
profilePicture: profile.picture
});
}

return user;
});

Login with a Discord Provider

warning

Important: When using the Discord provider on login routes, make sure you use gatekeeper.authenticateWithProvider(yourDiscordProvider) in a GET route, as the user will be redirected to Discord's sign in page

router.get(
'/auth/discord',
gatekeeper.authenticateWithProvider(DiscordAuth), (req, res) => {
return res.redirect('/profile');
}
);