Unfortunately, there is no "one size fits all" solution because each framework handle SSR differently (and even in a single framework there is more than one way of doing things).
But in general, the idea is to use a cookie based flow:
Create a new
XGenClient
instance for each server-side request"Load/Feed" your
xg.authStore
with data from the request cookiePerform your application server-side actions
Before returning the response to the client, update the cookie with the latest
xg.authStore
state
All BaseAuthStore
instances have 2 helper methods that should make working with cookies a little bit easier:
// update the store with the parsed data from the cookie string
xg.authStore.loadFromCookie('xgen_token=...;xgen_user=...;xgen_session=...');
// exports the store data as cookie, with option to extend the default SameSite, Secure, HttpOnly, Path and Expires attributes
xg.authStore.exportToCookie({ httpOnly: false }); // Output: 'xgen_token=...;xgen_user=...;xgen_session=...'
Below you can find an example of how to integrate with SvelteKit SSR:
SvelteKit
One way to integrate with SvelteKit SSR could be to create the XGen client in a hook handle and pass it to the other server-side actions using the event.locals
.
// src/hooks.server.js
import XGenClient from '@xgenai/sdk-core';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
event.locals.xg = new XGenClient({/*params*/});
// load the store data from the request cookie string
event.locals.xg.authStore.loadFromCookie(event.request.headers.get('cookie') || '');
const response = await resolve(event);
// send back the default 'xgen_token', 'xgen_user', 'xgen_session' cookies to the client with the latest store state
response.headers.append('set-cookie', event.locals.xg.authStore.exportToCookie());
return response;
}
And then, in some of your server-side actions, you could directly access the previously created event.locals.xg
instance:
// src/routes/recommendations/+server.js
/**
* Creates a `POST /recommendations` server-side endpoint
*
* @type {import('./$types').RequestHandler}
*/
export async function POST({ request, locals }) {
const { email, password } = await request.json();
const results = await xg.recommend.getResultsById({elementId: '<element_id>'})
return new Response(results);
}
For proper locals.xg
type detection, you can also add XGenClient
in your your global types definition:
// src/app.d.ts
import XGenClient from '@xgenai/sdk-core';
declare global {
declare namespace App {
interface Locals {
xg: XGenClient
}
}
}