How to add Discord OAuth to your SvelteKit web application

Creating a new SvelteKit project

npm init svelte@next
npm install cookie

Creating a Discord application

Creating a new application
Attention: NEVER SHARE CLIENT SECRET WITH ANYONE. If you don’t find these under General, check OAuth2 tab.
Set Redirect URI to http://localhost:3000/api/callback
  1. Start by creating .env file in your project root.
  2. Set it’s content to following:
VITE_DISCORD_API_URL="https://discordapp.com/api"
VITE_DISCORD_CLIENT_ID="YOUR-CLIENT-ID"
VITE_DISCORD_CLIENT_SECRET="YOUR-CLIENT-SECRET"
VITE_DISCORD_REDIRECT_URI="http://localhost:3000/api/callback"
VITE_HOST="http://localhost:3000"

Creating A Discord Authentication API

what your src/routes/api should look like now

routes/api/auth.js

npm run dev -- --open
If you’re receiving error about URI being wrong, make sure the REDIRECT URI in your .env file is “http://localhost:3000/api/callback” as well as in your Discord app OAuth2 settings. Note that it’s HTTP not HTTPS.

routes/api/callback.js

routes/api/refresh.js

routes/api/signout.js

Reading user token on session

Accessing the Discord user object in Svelte layouts

Let’s recap what we have built:

  • Each time an user goes to /api/auth path, they are taken to Discord’s authentication service.
  • After authenticating, Discord auth service returns the user to /api/callback which then returns the user to front-page with Discord tokens set in cookies.
  • User access token is saved in cookies for 10 minutes and refresh token is for 30 days. If access token expires, we use refresh token to fetch new access token.
  • Discord user object can be accessed via session object during loading of a page via session.user
  • User can clear their session by going to /api/signout or clicking the sign out button on front-page.

--

--

--

I build complex things on the web and share my findings to help others learn too.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Demo: A vacation-planning app for the savvy traveler

Next.js — React Server-Side Rendering Done Right

Are They Same Array? Check Using Concatenation

Realtime Chat Application with Socket.io and React - Part 1

Understanding the Event Emitter in the Nodejs

he Event Emitter Class In Nodejs

Flow: What’s the verdict?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mika S.

Mika S.

I build complex things on the web and share my findings to help others learn too.

More from Medium

Styling Remix App with Tailwind

Adding Metamask authentication in Next.js application using the thirdweb

Complete email/password authentication with firebase-9 and nextjs.

How to add Google AdSense in your Nextjs?

How to add Google AdSense in your Nextjs By Rajdeep Singh