Working with Discord OAUTH2 in JS



Discord Oauth2 in NodeJS

Last Updated: August 14, 2022











Table of Contents



1. Introduction
2. Setup
3. Code
4. Conclusion

Table of Contents



1. Introduction
2. Setup
3. Code
4. Conclusion



The Guide



The full code is available on Github here.

Discord OAUTH2 is a system that allows users to login to an external website (such as a personal blog or bot dashboard) with Discord. It shares limited information about the user, such as the ID, user tag, or even email. The information Discord gives regarding the user must be specified in the Discord developer portal and the user will typically be asked to allow Discord to share that limited data with the external website while logging in. OAUTH, also known as OAuth or Open Authentication, is a system that allows large websites to grant third-party applications limited information on a user when the user grants access to the third-party app/website. This allows users to sign in to many websites accross the web by logging in with one website and granting access to the third-party application. This system can be complex at first, but overall it is worth the effort to implement. This example will use Node.js.

Setup in the Discord Developer Portal

To start, you will need to create an application in the Discord Developer Portal. To do so, first login with your regular Discord account then press "New Application" at the top right corner.
Create the application button
When you click on the "New Application" button, a popup will open and it will prompt you for the application name (and possibly team). Enter your application name in the designated space then click "Create" or press Enter.
Step 2
Next, click on the OAuth2 tab.
Step 3
Make a note of your Client ID and Client Secret. They will be used later.
Step 4 image
Click "Add Redirect" then type http://localhost:80 into the box and save your changes.
limg5
Then, navigate to the URL Generator section under OAuth2, select "Identify" from the scopes box , and select your redirect URL from the dropdown menu. You should see a link form in the output box labeled below "Generated URL". Copy that link (either with CTRL/CMD C or with the copy button next to it) and save it somewhere. It will come in handy.

The Code



To actually program and integrate Discord Oauth2 in your program, we must first understand what steps are needed in order to do so. For this tutorial, I will be using Express, which is a NodeJS library. First, open a terminal (you can do so by opening a command prompt in Windows or using one in your code editor). You will need to install several dependencies. Be sure you have Node.js and npm intsalled first. They consist of the following: To install the dependencies, enter the following command in your powershell terminal (in VSCode, click on Terminal, then click "New Terminal"):
npm i express url axios path body-parser node-fetch

Each of these dependencies will play a part in the code. Express is for node.js web servers, URL will be used for creating URL search parameters, axios will be used to fetch data from APIs, etc. First, create an oauth.js file. For simplicity, I named it oauth.js, but you are free to name it however you would like. First, we will want to "import", or "require" our dependencies. To do so, enter the following code.
This chunk of code defines all the dependencies we will be using in our code. If you run the program in your terminal (node oauth.js), you shouldn't get any errors. If you do get any, you probably didn't install the dependencies correctly. Next, let's define our bot variables. Remember when you got the Client ID and Client Secret? Those will come in handy now. This tells the program your client info so the program can later make a request to the Discord API with that info. Next, let's define some more things. The above code creates a new express application and creates a function that will generate headers for a Discord API request. Next, let's configure our app to be able to read and interpret inputs in POST and GET requests.
The code above helps our app parse incoming requests of different types. Next, let's handle the default GET request that will trigger once you visit http://localhost:(port)/. To do this, we will use the app.get() function. In the code above, when the server receives a GET request, it will send the index.html file (we haven't created it yet, we'll save that for last). The app.get() method first takes the path, in this case just a "/". The second input is a callback function, which we used arrow function syntax for.
Alright. Let's get into the bulkier code. Let's make our server handle POST requests to /user. This will get the info on that user from the Discord API. To start, we will use app.post(). Let's enter the following into oauth.js: Notice that the code above won't actually do much. To actually understand how to get the user info, let's take a look at how OAuth works. First, the user will click a link to be redirected to a login portal. Once they login through the portal, they will be redirected back to our page with a code. We can then make a request to the Discord API with that code to retrieve an access token. With that access token, we can make one final request to the Discord API to get the user's actual info, such as username, ID, tag, etc. Our index.html file will send a POST request to the /user path with the code we initially get from logging in through the portal. Our req.body will be the code OAuth2 gives the user's browser when redirecting the user. To get the access token, we will have to make a request to the Discord API with certain parameters. This is where the URL dependency comes in hand. We can use it to construct the parameters we must send to the API.
Replace the existing app.post() with this new one:
When the server receives a POST request, it will now construct form data. That's not all! Before moving on though, let me explain what is happening. The server will first create a constant, data_1, then assign data to it. It will give the basic info (client ID, client secret (yes, that's what they are used for in this case!)), the grant type, redirect URI, scope, and code. The grant type is essentially what you want or need from the API. In this case, we're looking for the authorization token. The redirect URI is where the users was redirected. It should be the same as the one you put in the developer portal. The scope is what kind of information you are looking for on the user. In this case, we only selected Identify. You can add more by selecting the appropriate ones in the developer portal and adding them into the link and where the scope is appended to the data. If you add more, be sure to add a %20 in between each scope. Finally, we have the code. The code is the initial code the user got from being redirected from the login link. That's all the data. Next thing to do is to make a request to the Discord API. We'll be using node-fetch initially. We'll want to make a POST request. Replace your app.post() function with this.
In the code above, we package the data then make a POST request to the Discord API for the authorization token. Once it gets a response, .then() will activate, and the response will be converted to a JSON format. Then when that is done, it takes the response in a JSON format and is then ready to execute the next part of the code. We're almost done. What comes next is making yet another request to the Discord API to get the user info. This is the final one in this file. We will be using Axios for this request. Inside of the fetch() function last callback (where it goes data => {), enter the following code.
What this code does is it makes a request with axios to the user info endpoint in the Discord API. It will then send the username to wherever the request originates from (in this case, it should be the index.html file (still yet to be made)). In the event of an error, it will send a status 500 code (internal server error code).

Just a few more lines to go. Now, if you run the program, you won't get any result when you try to load the page. That's because the server isn't listening. To complete the oauth.js file, paste this code at the end.
This code will tell the app to start listening for requests and once it is up and running, you will get a message in the console.

index.html



We're done with the bulk of this code! All that is left is to create the HTML file, which should go by quickly. I'm not going to spend too much time going over it, as there is a lot of room for users to expand the file and design on. The code is as follows:
In essence, this code is basic HTML code that will display a button that will link you to your Discord OAuth2 link. When you are redirected with a code, it will detect the code and make a POST request to your server. When it gets a response, it will display it on a page. Be sure to paste your OAuth2 link where index.html states [DISCORD OAUTH LINK HERE].

Conclusion



You've made a web server that supports logging in with Discord OAuth2! Congrats! Before running the program, make sure you have pasted in your Client ID and Client Secret (in oauth.js) and pasted your OAuth2 link where it goes in the index.html file. If you changed the port, be sure to change the port variable AND the POST request link in oauth.js and index.html, respectively.

To run the program, type node oauth.js in your console and navigate to your localhost address. Click on "Login With Discord", login, wait a second or two, and it should work!

If you would like the full code, you can find it here. You can also report any errors you encounter there.
Happy coding!



Summary


To set up Discord OAUTH2 with Node.JS, first log into the Discord Developer portal. Next, navigate to the application you would like to set up OAUTH2 with, or create a new application. Then, navigate to the OAUTH2 tab and make a note of your Client ID and Client Secret. These will tell the Discord API which application is being used. Click “Add Redirect” then type your redirect URI. If you are hosting your own program, add a localhost domain. That is everything required from the Dev Portal. The next thing to do is install dependencies and set up your backend code. Finally, set up your front end HTML page and run the program. The code required can be found above or on GitHub.