New SvelteKit course: fullstacksveltekit.com

OAuth with Google

Use Google OAuth 2.0 to authenticate users in your SvelteKit app

Live Demo

Technologies

How to use

First, start by cloning this folder. We will use tiged for cloning subdirectories in Git repositories.

code loading...

Next, install the dependencies:  pnpm i.

Duplicate the .env.example file and rename it to .env.

There is already a migration file for the database, located in src/lib/server/db/migrations/0000_illegal_exiles.sql . This file is used to create the tables and indexes for the database. You can use this file as a starting point for your migration.

To run the migrations, run the following commands:

code loading...

Now, you can run the application:

pnpm run dev

Open your browser and navigate to http://localhost:5173 . You should see the home page with links to the login and signup pages.

Set up your Google Cloud project

First, you need to create a new Google Cloud project for your application. You can do this by going to the Google Cloud Console and creating a new project.

Once you have your project created, you need to add the following:

An OAuth consent screen

This is where you will add the information about your application and the scopes you want to request from the user. You can access the consent screen page by going to https://console.cloud.google.com/apis/credentials/consent?project=.

Make sure to add the following scopes for your application:

  • openid

And also, add a test email address in case you would like to test the login process with an email address besides the one used on your Google Cloud account.

A web application OAuth client ID

This is where you will create a new OAuth client ID for your application. You can access the client ID page by going to https://console.cloud.google.com/apis/credentials/oauthclient?project=.

The “Application type” should be set to “Web application”.

The “Authorized JavaScript origins” should be set to the URLs where your application will be accessible. In local, for SvelteKit, this is http://localhost:5173 . You can also add other origins, like the production URL of your application or staging or testing URLs.

The “Authorized redirect URIs” should be set to the URLs where your application will be redirected after the user has authorized your application. In local, for SvelteKit, this is http://localhost:5173/login/google/callback.

Once you have created your client ID, you will see a modal with the client ID and client secret. You will need to copy the client ID and client secret and update the values in the .env file.

Other Recipes