- Uses v10 of Discord API.
- Uses this SvelteKit template.
This is why I am here. Let's take this step by step :)
- Clone this repository to your development environment.
- Create a
.env
file in the root of the directory. - Create an app on discord.com/developers.
- On the OAuth2 settings tab, create a new Redirect URI with this value
http://localhost:3000/api/v1/user/auth
. This is our API endpoint that will be used to authenticate the user. - Add
http://localhost:3000/api/v1/user/auth
to your.env file
as a value toDISCORD_REDIRECT_URI
. - Under the URL generator settings tab (OAuth2->URL Generator), click the
identify
scope and theguilds
scope. - Add the generated URL to your
.env file
as a value toPUBLIC_DISCORD_AUTH_URI
. This is the URL the user will be redirected to, when they click the "discord" button. - Get the app's
client ID
andclient secret
from the General settings tab (OAuth2->General) and add them to your.env
file.
It should look something like this:
DISCORD_REDIRECT_URI=""
PUBLIC_DISCORD_AUTH_URI=""
DISCORD_OAUTH_CLIENT_ID=""
DISCORD_OAUTH_CLIENT_SECRET=""
For production, follow the steps again, but generate a new DISCORD_REDIRECT_URI
with your domain name instead of localhost:3000
- User clicks the
Login with Discord
button and they get redirected toPUBLIC_DISCORD_AUTH_URI
. - Assuming they successfully authorized our app in the Discord website, they will be redirected to our
DISCORD_REDIRECT_URI
, which is just a SvelteKit endpoint. Discord will append acode
query parameter that we can use to get user data from Discord's API. - In our endpoint we get the user data and the guilds they are in, then we create a new session in memory (with
sessionHandler
) and save the user data in it. Creating a session will return us a random ID that will be send back to the user as a cookie, just as we redirect them to/dashboard
. That is so... - When a user navigates to a protected route(eg. the
dashboard
folder), they send the cookie(automatically), then the cookie gets parsed in/src/hooks.ts
, and then authorized in the/src/routes/dashboard/__layout.svelte
. - And now, navigating to
localhost:3000/dashboard
should display the user's Discord ID.
- Type
FullUser
, is the authenticated user's access token properties(GrantData
) and user information properties(UserData
), in one type.
Contributions welcome ♥
Just open a new pull request.