Authentication

Houdini’s support for user sessions comes in 2 parts. First, you need to add a hooks.server.js file that defines the session for that user:

/// src/hooks.server.js

import { setSession } from '$houdini'

export async function handle({ event, resolve }) {
	// get the user information however you want
	const user = await authenticateUser(event)

	// set the session information for this event
	setSession(event, { user })

	// pass the event onto the default handle
	return await resolve(event)
}

Then, you can use the session parameter passed to your client’s network function to access the information:

/// src/lib/client.ts

import { HoudiniClient } from '$houdini'

async function fetchQuery({ fetch, text, variables = {}, session }) {
	const url = 'http://localhost:4000/graphql'; // usually coming from env
	const result = await fetch(url, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			Authorization: `Bearer ${session?.user.token}`
		},
		body: JSON.stringify({
			query: text,
			variables
		})
	})

	return await result.json()
}

export default new HoudiniClient(fetchQuery)

Remember, you can define types for your Session & Metadata by adding this to src/app.d.ts:

/// <reference types="@sveltejs/kit" />
declare namespace App {
	interface Session {
		token?: string | null
	}

	interface Metadata {
		abortController?: AbortController
	}
}