How to access sveltekit session in endpoint?

How do you access a session in an endpoint in sveltekit? I've tried this but no luck:

import { get } from 'svelte/store';    
import { getStores} from "$app/stores";

function getUser() { // <- call this at component initialization
  const { session } = getStores();
 
  return {
    current: () => get(session).user
  }
}

Upvotes: 3

Views: 10012

Answers (2)

Bob Fanger
Bob Fanger

Reputation: 29897

The session store only works inside svelte components, (it uses context under the hood) this provides isolation between users.

You can import the getSession() from src/hooks.js and pass the event to reuse the logic that extracts session data from the request.

Upvotes: 2

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

The session store is being populated in src/hooks.js, the normal flow to do so is

  1. in handle, add some data to event.locals.
  2. in getSession, use event.locals to create a session object.

This session object is available in the client as the session store, and on during ssr if you use the load functions, but it is not available in endpoints.

What is available though in the endpoint is the locals variable, that is originally passed to the getSession function, so you can read that one.

export async function get({ locals }) {
  // code goes here
}

Just be aware that this means there is no synchronization between locals and the client side session, if you add something to the session it will not be available to the endpoint. To handle this you would have to for example add new data to the cookie and parse this in the handle function.

Upvotes: 9

Related Questions