title: Sveltekit - Access session from lib
body: <p>I'm using Sveltekit with Typescript. In <code>$lib</code> folder, I have an <code>api.ts</code> file.</p>
  <p>After login, I'm writing JWT token to <code>session</code> and wanted to use it in <code>api.ts</code> file. But I'm getting an error.</p>
  <p>I'm following this example:
  <a href="https://github.com/sveltejs/realworld/blob/master/src/routes/login/index.svelte" rel="noreferrer"> sveltejs / realworld </a></p>
  <pre class="lang-js prettyprint-override"><code>// login.svelte
  
  import { session } from &quot;$app/stores&quot;;
  
  // After login...
  
  $session.accessToken = response.accessToken;
  
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>// api.ts
  
  import { session } from &quot;$app/stores&quot;;
  
  // Before sending request...
  
  if ($session.accessToken) {
      // Add Bearer token to header...
  }
  </code></pre>
  <p>Error: <code>Cannot find name '$session'. Did you mean 'session'?ts(2552)</code></p>
  <p>Why this <code>$session</code> thing works in <code>.svelte</code> file, but not in <code>.ts</code> file?</p>
  <p>How can I access <code>accessToken</code> in <code>session</code> from <code>.ts</code>?</p>
  <p>Thanks.</p>
  <hr />
  <p><strong>Edit</strong></p>
  <p><code>api.ts</code> code:</p>
  <pre class="lang-js prettyprint-override"><code>import { get as getStore } from &quot;svelte/store&quot;;
  import { session } from &quot;$app/stores&quot;;
  
  const base = &quot;https://localhost:44300&quot;;
  
  async function send(method: string, path: string, data?: unknown) {
    const opts = {
      method,
      headers: {},
      body: &quot;&quot;
    };
  
    if (data) {
      opts.headers[&quot;Content-Type&quot;] = &quot;application/json&quot;;
      opts.body = JSON.stringify(data);
    }
  
    const { accessToken } = getStore(session);
  
    if (accessToken) {
      opts.headers[&quot;Authorization&quot;] = `Bearer ${accessToken}`;
    }
  
    return fetch(`${base}${path}`, opts)
      .then((r) =&gt; r.text())
      .then((json) =&gt; {
        try {
          return JSON.parse(json);
        } catch (err) {
          return json;
        }
      });
  }
  
  export function get&lt;T&gt;(path: string): Promise&lt;T&gt; {
    return send(&quot;GET&quot;, path);
  }
  
  export function post&lt;T&gt;(path: string, data: unknown): Promise&lt;T&gt; {
    return send(&quot;POST&quot;, path, data);
  }
  
  export function put&lt;T&gt;(path: string, data: unknown): Promise&lt;T&gt; {
    return send(&quot;PUT&quot;, path, data);
  }
  
  export function del&lt;T&gt;(path: string, data: unknown): Promise&lt;T&gt; {
    return send(&quot;DELETE&quot;, path, data);
  }
  </code></pre>