Skip to main content

SvelteKit

View a live deployed version.

info

We will use the Phase Two SvelteKit example code here, but the logic could easily be applied to any existing application.

  1. Clone the Phase Two example repo.
  2. Open the SvelteKit folder within /frameworks/sveltekit.
  3. Run npm install and then npm run dev. This example leverages @auth/sveltekit to provide HOC support.
  4. The project makes use of the following SvelteKit items: hooks, components, layout, and @auth/sveltekit module. We'll review each in kind.
  5. We'll review where we configure out Keycloak instance. Open the src/auth.ts file. This is a server only file. We will be updating a few values from the prior section where we set up our OIDC client. Taking the values from the OIDC Client Config section, set those values in the code. While it is recommended to use Environment variables for the secret, for the purpose of this tutorial, paste in the Client secret from the OIDC client creation section for the value of clientSecret.
// Use Environment Variables AUTH_SECRET in prod
const authjsSecret =
"f18d48ce9bea32e44b5591b2c89185729d4559435f77ca76872a83a0850563a4";

const realm = "shared-deployment-001";

const kcConfig = {
// Use Environment Variables AUTH_KEYCLOAK_ISSUER in prod
issuer: `https://usw2.auth.ac/auth/realms/${realm}`,
// Paste "Client id" here. Use Environment Variables AUTH_KEYCLOAK_ID in prod
clientId: "reg-example-1",
// Paste "Client secret" here. Use Environment Variables AUTH_KEYCLOAK_ISSUER in prod
clientSecret: "CLIENT_SECRET",
};

Those are used to popluate the config for the provider Keycloak:

export const { handle, signIn, signOut } = SvelteKitAuth({
trustHost: true,
secret: authjsSecret,
providers: [Keycloak(kcConfig)],
});
  1. Next, let's review the hooks (src/hooks.server.ts) file. This imports the handle method by the src/auth.ts and re-exports it. This allows the hooks to act as a middleware and include the authentication status of the user in each request.
export { handle } from "./auth.js";
  1. To retrieve the authentication status of the user in server-side rendering on the index route, it's using the +layout.server.ts file. It retrieves the authentication status via the getSession function from SvelteKit Locals set by src/hook.server.ts.
import type { LayoutServerLoad } from "./$types.js";

export const load: LayoutServerLoad = async (event) => {
const session = await event.locals.getSession();
return {
session,
};
};
  1. The server-side authentication data is then accessed inside the +page.svelte, and then passed onto the user (src/components/user.svelte) component as follows:
<script lang="ts">
import User from "$components/user.svelte";
import type { LayoutServerData } from "./$types.js";

export let data: LayoutServerData;
</script>

// ... Rest of the index route ... // <User data={{ user: data?.session?.user,
status: Boolean(data?.session), }} />

The props, user and status represent the user information object and whether the user is signed in, respectively.

  1. At this point our entire application will be able to access all information and methods needed to perform authentication. View src/components/user.svelte for exactly how the code is authenticating your user. The sections rendering the Log in and Log out buttons are conditional areas based on the authenticated context. The buttons invoke server-side APIs provided by @auth/sveltekit.

The logic using the authenticator to conditionally determine the Authenticated state, can be used to secure routes, components, and more.

  1. Open localhost:3000. You will see the Phase Two example landing page. You current state should be Not authenticated. Click Log In. This will redirect you to your login page.
info

Use the non-admin user created in the previous section to sign in.

  1. Enter the credentials of the non-admin user you created. Click Submit. You will then be redirected to the application. The Phase Two example landing page now loads your Authenticated state, displaying your user's email and name.
  2. Neat! If you clear the browser state for that tab, then you will have to be redirected away to sign-in again.