Google Login with sveltekit in less than 5min!

Rahulserver
3 min readNov 23, 2023

--

Based on what I did in my recent project, I would show how to integrate google authentication to an existing sveltekit application in a minimalistic way(something i couldn’t find in any resources across the web as of now). Also you would learn how to protect server side (api endpoints) and client side (pages). The article assumes you have already generated google credentials required for google login(the nuances of which would be a part of a future article).

And if everything goes according to plan, it shouldn’t take you over 5min. to add it!

Let’s see…

Step 1:

Install auth.js library

npm install --save @auth/core @auth/sveltekit

Step 2:

Add google credentials to the .env file (in project root outside of src folder).

This should contain these vars(the values placed here are imaginary. replace with your own):

GOOGLE_CLIENT_ID=217276797395-5c7abia7hktpqtfd68f5pmrhctfnwhk1.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=AOMSPX-n8g0rFndTqSrcMvyuvdM1xrUoZwl
AUTH_SECRET=somesecret

Don’t forget to add the AUTH_SECRET. Its just a random string needed for the auth.js library.

Step 3:

Update (or create if not already created) src/hooks.server.js file.

In this file, add these lines to use the google login provider exported by auth.js libraries

import { SvelteKitAuth } from "@auth/sveltekit" 
import {GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET} from "$env/static/private"
import Google from "@auth/core/providers/google";
export const handle = SvelteKitAuth({ providers: [Google({ clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET })] });

Step 5:

In order to add session checks before loading every page, add this to src/routes/+layout.server.js

export const load = async (event) => {
return {
session: await event.locals.getSession(),
}
}

Step 4:

Add the signIn or signOut functions exported by auth.js into your component where you want to show the UI element(button or link or anything). Use the page store’s $page.data.session to conditionally render elements. For simplicity, in this case we are adding this to the src/routes/+page.svelte (the root page) which looks like this:

<script>
import {signIn, signOut} from "@auth/sveltekit/client"
import {page} from "$app/stores";
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
<p>
{#if $page.data.session}
<span>
<small>Signed in as</small><br/>
<strong>{$page.data.session.user?.name ?? "User"}</strong>
</span>
<button on:click={() => signOut()} class="button">Sign out</button>
{:else}
<span>You are not signed in</span>
<button on:click={() => signIn("google")}>
Sign In with Google
</button>
{/if}
</p>

Step 5:

To protect the API routes, use the locals.getSession() to find out if a user is authenticated or not in a server side route(you can get the authenticated user using session.user object). For example in my sample project, I have an endpoint in src/routes/api/module1/+server.js where the GET request handler is protected using this approach.

import {error, json} from "@sveltejs/kit";export async function GET({url, locals, cookies}) {
let session = await locals.getSession();
if(!session) {
throw error(401, "Forbidden");
} return json({
success: true,
authenticatedUser: session.user
});
}

Step 6:

Protect Client side routes using the onMount function callback to check for the $page.data?.session and as added security add a check for the same thing in an if block in the markup. To demonstrate this, I have created a src/routes/protected/+page.svelte which looks like this:

<script>
import { onMount } from 'svelte';
import {page} from "$app/stores";
import {goto} from "$app/navigation"; onMount(() => {
if(!$page.data?.session) {
goto('/');
return;
}
});
</script>
{#if $page.data?.session}
<div>Protected</div>
{/if}

Thats it you have successfully integrated your google login in a sveltekit app within 5min.!

The code accompanying this article can be found in this github repo.

Note: there could be a few places you could get stuck. Particularly with generating the google credentials, redirect urls, authorised origins. There are certain nuances to it that are worth considering. I will touch the topic in another blog post coming very soon. Till then, enjoy some svelty-coding :D

#sveltekit #sveltejs #sveltekit #rahulserver #nodejs #authjs

--

--

Rahulserver

Software consultant with over 11 yrs experience working with startups. DM me on twitter for business. .