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:

Creating A Discord Authentication API

what your src/routes/api should look like now


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.




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

Language detection strategy in server-side rendered JavaScript

Build a Captcha Generator Using JavaScript

Deploy your React App with Firebase Hosting

[LeetCode][436. Find Right Interval][Medium]

8 Frontend Coding Ideas That Will Inspire You To Code


Get started with web workers

How To Add HTML Wrapper On Angular Component In Storybook

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

Animated display images one after one with VueJS & TailwindCSS

JAMStack hosting providers and the future of web development (Cloudflare + FaunaDB)

How to deploy a SvelteKit app with the node-adapter

Ionic 6 + Svelte 🚀