### Install Project Dependencies Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Install all necessary dependencies for the SDK project. ```bash npm install ``` -------------------------------- ### Install Playwright for Testing Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Install Playwright, a web testing framework, for testing the SDK. You can install all browsers or specific ones like Chromium. ```bash npx playwright install ``` ```bash npx playwright install chromium ``` -------------------------------- ### Obtain Management API Token with Client Credentials Grant Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use `getToken` in a server route to get a machine-to-machine access token for the Kinde Management API. Requires `KINDE_AUDIENCE` to be set in your environment variables. ```typescript // src/routes/api/users/+server.ts import { getToken } from '@kinde-oss/kinde-auth-sveltekit'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const token = await getToken(); // token is a raw JWT string const response = await fetch('https://your-domain.kinde.com/api/v1/users', { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', }, }); if (!response.ok) { return new Response('Failed to fetch users', { status: response.status }); } const users = await response.json(); return new Response(JSON.stringify(users), { headers: { 'Content-Type': 'application/json' }, }); }; ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Change your current directory to the cloned SDK project. ```bash cd kinde-sveltekit-sdk ``` -------------------------------- ### Configure Environment Variables for Testing Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Set up the .env file with your Kinde API credentials and configuration for testing. ```bash KINDE_AUDIENCE=your_kinde_api KINDE_CLIENT_ID=your_kinde_client_id // Please use an application with password method KINDE_CLIENT_SECRET=your_kinde_client_secret KINDE_COOKIE_DOMAIN=// domain to assign cookie to KINDE_ISSUER_URL=https://your_kinde_domain.kinde.com KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:4173 KINDE_POST_LOGOUT_REDIRECT_URL=http://localhost:4173 KINDE_REDIRECT_URL=http://localhost:4173/api/auth/kinde_callback KINDE_SCOPE=profile email offline openid KINDE_USER_EMAIL_TEST= // An user has existed in your organization KINDE_USER_PASSWORD_TEST= KINDE_AUTH_WITH_PKCE= // Set `true` if you want to use Authentication Code Flow with PKCE KINDE_DEBUG= // Set `true` if you want to enable the `api/auth/health` endpoint ``` -------------------------------- ### Build the Kinde SvelteKit SDK Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Compile the SDK after making modifications. ```bash npm run build ``` -------------------------------- ### Pack and Add SDK to Existing Project Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Package the SDK for use in another project and update its package.json. ```bash npm pack ~/Documents/Projects/kinde-sveltekit-sdk ``` ```json { ... "dependencies": { "@kinde-oss/kinde-sveltekit-sdk": "file:kinde-oss-kinde-sveltekit-sdk-.tgz", ... } ... } ``` -------------------------------- ### Clone Kinde SvelteKit SDK Repository Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Use this command to clone the SDK repository to your local machine. ```bash git clone https://github.com/kinde-oss/kinde-sveltekit-sdk ``` -------------------------------- ### Run SDK Tests Source: https://github.com/kinde-oss/kinde-sveltekit-sdk/blob/main/README.md Execute the test suite for the Kinde SvelteKit SDK. ```bash npm run test ``` -------------------------------- ### Typed Management API Client — `getConfiguration` Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt `getConfiguration` builds a `Configuration` object (from `@kinde-oss/kinde-typescript-sdk`) pre-loaded with a fresh access token. Pass it directly to any generated Management API client class, optionally overriding fields such as `basePath`. ```APIDOC ## Typed Management API Client — `getConfiguration` `getConfiguration` builds a `Configuration` object (from `@kinde-oss/kinde-typescript-sdk`) pre-loaded with a fresh access token. Pass it directly to any generated Management API client class, optionally overriding fields such as `basePath`. ```typescript // src/routes/api/feature-flags/+server.ts import { getConfiguration } from '@kinde-oss/kinde-auth-sveltekit'; import { FeatureFlagsApi } from '@kinde-oss/kinde-typescript-sdk'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { // Optionally override configuration fields const config = await getConfiguration({ // basePath: 'https://custom-domain.kinde.com', // override if needed }); const flagsApi = new FeatureFlagsApi(config); const flags = await flagsApi.getFeatureFlags(); return new Response(JSON.stringify(flags), { headers: { 'Content-Type': 'application/json' }, }); }; ``` ``` -------------------------------- ### Create Typed Management API Client Configuration Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use `getConfiguration` to build a `Configuration` object for the Kinde Management API client. This object is pre-loaded with an access token and can optionally override configuration fields like `basePath`. ```typescript // src/routes/api/feature-flags/+server.ts import { getConfiguration } from '@kinde-oss/kinde-auth-sveltekit'; import { FeatureFlagsApi } from '@kinde-oss/kinde-typescript-sdk'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { // Optionally override configuration fields const config = await getConfiguration({ // basePath: 'https://custom-domain.kinde.com', // override if needed }); const flagsApi = new FeatureFlagsApi(config); const flags = await flagsApi.getFeatureFlags(); return new Response(JSON.stringify(flags), { headers: { 'Content-Type': 'application/json' }, }); }; ``` -------------------------------- ### Catch-all Auth Route Handler in SvelteKit Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Implement a single SvelteKit server route to handle all Kinde authentication endpoints by delegating to the handleAuth function. This file should be located at src/routes/api/auth/[...kindeAuth]/+server.ts. ```typescript // src/routes/api/auth/[...kindeAuth]/+server.ts import { handleAuth } from '@kinde-oss/kinde-auth-sveltekit'; import type { RequestEvent } from '@sveltejs/kit'; export function GET(event: RequestEvent): Promise { return handleAuth(event); } ``` -------------------------------- ### Post-Login Redirect Configuration Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Configure a post-login redirect by passing `post_login_redirect_url` as a query parameter to the login or registration endpoints. The SDK validates the URL to prevent open redirects. ```svelte Log in to view report Log in to view report ``` -------------------------------- ### Environment Variable Configuration for Kinde Auth Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Configure Kinde authentication by setting these environment variables in your .env file. Ensure all required variables are present for proper SDK operation. ```bash # .env KINDE_ISSUER_URL=https://your-domain.kinde.com KINDE_CLIENT_ID=your_client_id KINDE_CLIENT_SECRET=your_client_secret KINDE_REDIRECT_URL=http://localhost:5173/api/auth/kinde_callback KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:5173/dashboard KINDE_POST_LOGOUT_REDIRECT_URL=http://localhost:5173 KINDE_AUDIENCE=https://your-domain.kinde.com/api # optional, for Management API KINDE_SCOPE=profile email offline openid KINDE_AUTH_WITH_PKCE=false # set to "true" to use PKCE (omits client_secret) KINDE_COOKIE_DOMAIN=localhost # domain used for session cookies KINDE_DEBUG=false # set to "true" to expose the /api/auth/health endpoint ``` -------------------------------- ### Management API Headers — `getHeaders` Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt `getHeaders` is a convenience wrapper around `getToken` that returns a ready-to-use headers object with `Authorization` and `Accept` pre-populated. ```APIDOC ## Management API Headers — `getHeaders` `getHeaders` is a convenience wrapper around `getToken` that returns a ready-to-use headers object with `Authorization` and `Accept` pre-populated. ```typescript // src/routes/api/organisations/+server.ts import { getHeaders } from '@kinde-oss/kinde-auth-sveltekit'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const headers = await getHeaders(); // headers = { Authorization: 'Bearer ', Accept: 'application/json' } const res = await fetch('https://your-domain.kinde.com/api/v1/organizations', { headers, }); const data = await res.json(); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' }, }); }; ``` ``` -------------------------------- ### Generate Management API Headers with Authorization Token Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use `getHeaders` as a convenience function to create a headers object including the Authorization token and Accept header, ready for use with Kinde Management API fetch requests. ```typescript // src/routes/api/organisations/+server.ts import { getHeaders } from '@kinde-oss/kinde-auth-sveltekit'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const headers = await getHeaders(); // headers = { Authorization: 'Bearer ', Accept: 'application/json' } const res = await fetch('https://your-domain.kinde.com/api/v1/organizations', { headers, }); const data = await res.json(); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' }, }); }; ``` -------------------------------- ### Health Check Endpoint Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt When KINDE_DEBUG is enabled, this endpoint provides a diagnostic summary of the SDK configuration. It's useful for verifying environment variables during local development. ```bash # Requires KINDE_DEBUG=true in .env curl http://localhost:5173/api/auth/health # Expected response: # { # "authDomain": "https://your-domain.kinde.com", # "clientId": "your_client_id", # "logoutRedirectURL": "http://localhost:5173", # "redirectURL": "http://localhost:5173/api/auth/kinde_callback", # "audience": "https://your-domain.kinde.com/api", # "scope": "profile email offline openid", # "clientSecret": "Set correctly", # "loginRedirectURL": "http://localhost:5173/dashboard", # "authUsePKCE": false, # "version": "2.2.3", # "framework": "sveltekit" # } ``` -------------------------------- ### Svelte Component for Login Link Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use the `LoginLink` Svelte component to create a button that redirects users to the Kinde login page. It accepts an `options` prop to customize login behavior, such as specifying an organization code, connection ID, or post-login redirect URL. ```svelte Sign in with Google ``` -------------------------------- ### Management API Token — `getToken` Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt `getToken` uses the Client Credentials grant to obtain a machine-to-machine access token for the Kinde Management API. Requires `KINDE_AUDIENCE` to be set to `https://your-domain.kinde.com/api`. ```APIDOC ## Management API Token — `getToken` `getToken` uses the Client Credentials grant to obtain a machine-to-machine access token for the Kinde Management API. Requires `KINDE_AUDIENCE` to be set to `https://your-domain.kinde.com/api`. ```typescript // src/routes/api/users/+server.ts import { getToken } from '@kinde-oss/kinde-auth-sveltekit'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const token = await getToken(); // token is a raw JWT string const response = await fetch('https://your-domain.kinde.com/api/v1/users', { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', }, }); if (!response.ok) { return new Response('Failed to fetch users', { status: response.status }); } const users = await response.json(); return new Response(JSON.stringify(users), { headers: { 'Content-Type': 'application/json' }, }); }; ``` ``` -------------------------------- ### `LoginLink` Component Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt A pre-built Svelte button component that redirects the user to `/api/auth/login`. Accepts an `options` prop for passing `LoginMethodParams` (e.g., `org_code`, `connection_id`, `post_login_redirect_url`). ```APIDOC ## `LoginLink` Component A pre-built Svelte button component that redirects the user to `/api/auth/login`. Accepts an `options` prop for passing `LoginMethodParams` (e.g., `org_code`, `connection_id`, `post_login_redirect_url`). ```svelte Sign in with Google ``` ``` -------------------------------- ### Accessing the Authenticated User — `kindeAuthClient` Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use `kindeAuthClient` in `+page.server.ts` or `+layout.server.ts` load functions to access the authenticated user's profile, permissions, organisation, and feature flags. ```APIDOC ## Accessing the Authenticated User — `kindeAuthClient` `kindeAuthClient` is a pre-configured instance of the Kinde server client. Use it in `+page.server.ts` or `+layout.server.ts` load functions to read the authenticated user's profile, permissions, organisation, and feature flags. ```typescript // src/routes/dashboard/+page.server.ts import { kindeAuthClient } from '@kinde-oss/kinde-auth-sveltekit'; import { redirect } from '@sveltejs/kit'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ request }) => { const isAuthenticated = await kindeAuthClient.isAuthenticated(request as any); if (!isAuthenticated) { throw redirect(302, '/api/auth/login'); } const [user, permissions, organisation, featureFlags] = await Promise.all([ kindeAuthClient.getUser(request as any), kindeAuthClient.getPermissions(request as any), kindeAuthClient.getOrganization(request as any), kindeAuthClient.getFeatureFlags(request as any), ]); return { user, permissions, organisation, featureFlags }; }; // Expected shape of `user`: // { // id: "kp_1234567890abcdef", // given_name: "Jane", // family_name: "Doe", // email: "jane@example.com", // picture: "https://..." // } ``` ``` -------------------------------- ### Access Authenticated User Data in Server Load Function Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use `kindeAuthClient` in `+page.server.ts` or `+layout.server.ts` load functions to check authentication status and retrieve user profile, permissions, organization, and feature flags. Redirects to login if the user is not authenticated. ```typescript // src/routes/dashboard/+page.server.ts import { kindeAuthClient } from '@kinde-oss/kinde-auth-sveltekit'; import { redirect } from '@sveltejs/kit'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ request }) => { const isAuthenticated = await kindeAuthClient.isAuthenticated(request as any); if (!isAuthenticated) { throw redirect(302, '/api/auth/login'); } const [user, permissions, organisation, featureFlags] = await Promise.all([ kindeAuthClient.getUser(request as any), kindeAuthClient.getPermissions(request as any), kindeAuthClient.getOrganization(request as any), kindeAuthClient.getFeatureFlags(request as any), ]); return { user, permissions, organisation, featureFlags }; }; // Expected shape of `user`: // { // id: "kp_1234567890abcdef", // given_name: "Jane", // family_name: "Doe", // email: "jane@example.com", // picture: "https://..." // } ``` -------------------------------- ### PortalLink Component Usage Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use the PortalLink component to redirect authenticated users to the Kinde self-serve portal. It requires an active session and can be configured with custom labels and return URLs. ```svelte Manage Account ``` -------------------------------- ### Server Hook for Session Management in SvelteKit Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Integrate sessionHooks into your SvelteKit's handle hook in src/hooks.server.ts to manage session data via cookies. This enables session methods like getSessionItem, setSessionItem, and removeSessionItem. ```typescript // src/hooks.server.ts import { sessionHooks } from '@kinde-oss/kinde-auth-sveltekit'; import { redirect, type Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { // Auto-redirect invitation links to the registration flow const invitationCode = event.url.searchParams.get('invitation_code')?.trim(); const isAuthRoute = event.url.pathname.startsWith('/api/auth/'); if (invitationCode && !isAuthRoute) { const params = new URLSearchParams({ invitation_code: invitationCode, is_invitation: 'true', }); throw redirect(302, `/api/auth/register?${params.toString()}`); } // Attach Kinde session methods to event.request via cookies sessionHooks({ event }); return resolve(event); }; ``` -------------------------------- ### RegisterLink Component Usage Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt Use the RegisterLink component to create a button that redirects users to the registration API endpoint. It accepts options for pre-filling organization codes and specifying post-login redirect URLs. ```svelte Create account ``` -------------------------------- ### LogoutLink Component Usage Source: https://context7.com/kinde-oss/kinde-sveltekit-sdk/llms.txt The LogoutLink component provides a button to log users out, clear cookies, and redirect them. It supports custom redirect URLs and signing out all sessions. ```svelte Sign out everywhere ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.