OAuth Integration in Svelte

From the SvelteKit cheat sheet ยท Authentication ยท verified Nov 2026

OAuth Integration

Third-party authentication providers

javascript
// GitHub OAuth callback (+server.js)
import { error, redirect } from '@sveltejs/kit';
import { getGitHubToken, getGitHubUser } from '#lib/server/github.js';
import { createSession, findOrCreateUser } from '#lib/server/auth.js';

export async function GET({ url, cookies }) {
  const code = url.searchParams.get('code');
  const state = url.searchParams.get('state');

  // The state must match the cookie set before the redirect
  if (!state || state !== cookies.get('oauth_state')) {
    error(400, 'Invalid state');
  }

  // Exchange code for token
  const { access_token } = await getGitHubToken(code);

  // Get user info, then find or create the local user
  const githubUser = await getGitHubUser(access_token);
  const user = await findOrCreateUser(githubUser);

  // Create session
  const session = await createSession(user.id);
  cookies.set('session', session.id, { maxAge: 60 * 60 * 24 * 30 });

  redirect(303, '/');
}
๐Ÿ”‘ OAuth with GitHub, Google, etc.
โœ‰๏ธ Magic link authentication
๐Ÿ›ก๏ธ CSRF protection with state parameter
๐Ÿ“Œ Redirects to another origin need { external: true }

Continue with SvelteKit

Save the full cheat sheet or work through every related task.

More Svelte tasks

Back to the full SvelteKit cheat sheet