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);
}