How to add Discord OAuth to your Sapper web application

Creating a new Sapper project

npx degit "sveltejs/sapper-template#rollup" my-app
npm uninstall polka && npm install express

Creating a Discord application

Creating a new application
Attention: NEVER SHARE CLIENT SECRET WITH ANYONE.

Creating a Discord Authentication API

what your src/routes/api should look like now

routes/api/auth

Auth view is in user’s local language if it’s supported. If not, in English.

routes/api/callback

routes/api/refresh

routes/api/signout

Reading user tokens on each session

Modifying the server.js

Modifying _layout.svelte

Creating user dashboard

Let’s recap what we now have:

  • Each time user goes to /dashboard or /api/auth, they are taken to Discord for authentication
  • After authenticating, they are taken via /api/callback to either /dashboard or front page, depending if authentication was successful or not
  • 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.
  • User token and Discord user object can be accessed via session object during preload of a page (variables userToken and discordUser)
  • User can clear their session by going to /api/signout or clicking the sign out button on dashboard.

--

--

--

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

Automate WordPress recon for Bug Bounty | WordPress:Cheat sheet

Implement Javascript’s call() method yourself

Creating a Dev.to clone with React, Node, TypeScript, GraphQL and Apollo (Part 1)

React NextJS Create Instagram UI clone — Profile Page Part 3

TODO Desktop Application using React + electron.

Have Some Fiber in your Diet

Entering the Light of React and Nodejs Combo

Nullish coalescing operator: ‘??’

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

How to host your REST API/backend on a virtual private server (VPS)

Setting up RabbitMQ on mac with silicon chip(m1).

Set up CI using Github Action

Hosting Nodejs App using your own Docker Image in Jelastic PaaS/ Yeti Cloud