Authentication
houdini defers to SvelteKit’s sessions and/or metadata for authentication. Assuming that these args has been populated somehow, you can access it through arguments in the fetchQuery
definition:
// client.ts
import type { RequestHandlerArgs } from '$houdini'
import { HoudiniClient } from '$houdini'
// For Query & Mutation
async function fetchQuery({
fetch,
text = '',
variables = {},
session,
metadata
}: RequestHandlerArgs) {
// Prepare the request
const url = import.meta.env.VITE_GRAPHQL_ENDPOINT || 'http://localhost:4000/api/graphql'
// regular fetch (Server & Client)
const result = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${session?.token}` // session usage example
},
body: JSON.stringify({
query: text,
variables
})
})
// extract and assign the json body of the response to a variable
const json = await result.json()
// metadata usage example
if (metadata?.logResult === true) {
console.info(JSON.stringify(json, null, 2))
}
return json
}
// Export the Houdini client
export const houdiniClient = new HoudiniClient(fetchQuery)
You can also type your Session & Metadata as follow in src/app.d.ts
:
/// <reference types="@sveltejs/kit" />
declare namespace App {
interface Session {
token?: string | null
}
interface Metadata {
logResult?: boolean | null
}
}