Efe Erdoğru
Efe Erdoğru

Reputation: 121

Sveltekit - Access session from lib

I'm using Sveltekit with Typescript. In $lib folder, I have an api.ts file.

After login, I'm writing JWT token to session and wanted to use it in api.ts file. But I'm getting an error.

I'm following this example: sveltejs / realworld

// login.svelte

import { session } from "$app/stores";

// After login...

$session.accessToken = response.accessToken;

// api.ts

import { session } from "$app/stores";

// Before sending request...

if ($session.accessToken) {
    // Add Bearer token to header...
}

Error: Cannot find name '$session'. Did you mean 'session'?ts(2552)

Why this $session thing works in .svelte file, but not in .ts file?

How can I access accessToken in session from .ts?

Thanks.


Edit

api.ts code:

import { get as getStore } from "svelte/store";
import { session } from "$app/stores";

const base = "https://localhost:44300";

async function send(method: string, path: string, data?: unknown) {
  const opts = {
    method,
    headers: {},
    body: ""
  };

  if (data) {
    opts.headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(data);
  }

  const { accessToken } = getStore(session);

  if (accessToken) {
    opts.headers["Authorization"] = `Bearer ${accessToken}`;
  }

  return fetch(`${base}${path}`, opts)
    .then((r) => r.text())
    .then((json) => {
      try {
        return JSON.parse(json);
      } catch (err) {
        return json;
      }
    });
}

export function get<T>(path: string): Promise<T> {
  return send("GET", path);
}

export function post<T>(path: string, data: unknown): Promise<T> {
  return send("POST", path, data);
}

export function put<T>(path: string, data: unknown): Promise<T> {
  return send("PUT", path, data);
}

export function del<T>(path: string, data: unknown): Promise<T> {
  return send("DELETE", path, data);
}

Upvotes: 6

Views: 7691

Answers (2)

g012
g012

Reputation: 65

I want to add to the answer (but can't comment - lack of reput', so if it's inappropriate edit the actual answer to add the info, thanks); to Efe Erdogru and Raul Gomez:

The last line:

const { accessToken } = get(session);

cannot be at the top-level of the ts file. Do it in a function called from your Svelte file initialization block, so that at that point, the session is initialized.

Upvotes: 3

Connor Low
Connor Low

Reputation: 7186

$session is a svelte-specific syntax used to reactively access a store value. For one-time value access in a typescript file, use the get function:

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

const { accessToken } = get(session);

If you need a reactive solution, use session.subscribe instead.

Upvotes: 2

Related Questions