Add Gmail OAuth to a SvelteKit App
Add Gmail authentication to your SvelteKit app in two files. This guide assumes you already have a SvelteKit app running.
Prerequisites
- A SvelteKit app (using SvelteKit 1.0+)
- An inbox.dog API key (get one here)
Step 1: Set environment variables
Add your inbox.dog credentials to .env:
INBOX_DOG_CLIENT_ID=id_abc123...
INBOX_DOG_CLIENT_SECRET=sk_xyz789... Step 2: Create the OAuth redirect handler
Create src/routes/auth/gmail/+server.ts:
import { redirect } from '@sveltejs/kit';
import { INBOX_DOG_CLIENT_ID } from '$env/static/private';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url }) => {
const redirectUri = `${url.origin}/auth/gmail/callback`;
const authUrl = new URL('https://inbox.dog/oauth/authorize');
authUrl.searchParams.set('client_id', INBOX_DOG_CLIENT_ID);
authUrl.searchParams.set('redirect_uri', redirectUri);
authUrl.searchParams.set('scope', 'email');
throw redirect(302, authUrl.toString());
}; Step 3: Create the callback handler
Create src/routes/auth/gmail/callback/+server.ts:
import { redirect } from '@sveltejs/kit';
import { INBOX_DOG_CLIENT_ID, INBOX_DOG_CLIENT_SECRET } from '$env/static/private';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url }) => {
const code = url.searchParams.get('code');
if (!code) {
throw redirect(302, '/?error=no_code');
}
const response = await fetch('https://inbox.dog/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code,
client_id: INBOX_DOG_CLIENT_ID,
client_secret: INBOX_DOG_CLIENT_SECRET,
}),
});
const data = await response.json();
if (!response.ok) {
console.error('OAuth error:', data);
throw redirect(302, '/?error=oauth_failed');
}
// Store tokens in your database or session
// For this example, we'll just redirect with the email
const { email, access_token, refresh_token } = data;
// Save tokens to your database or session store
// Then use access_token with the Gmail API
throw redirect(302, '/');
}; Step 4: Add the connect button
In any +page.svelte file, add a link to start the OAuth flow:
<a href="/auth/gmail">
Connect Gmail
</a> That's it. When a user clicks the link, they'll authenticate with Google and return to your callback handler with tokens.
Next steps
- Handle token refresh — Keep access tokens valid beyond 1 hour
- Full API reference — Complete documentation for all endpoints