Different ways to get the sessionId for a custom API call

I need to attach the Bearer authorization header to a custom API call. I am currently getting the wasp:sessionId from localstorage, which is not ideal. If I'm not mistaken there was an endpoint to fetch the sessionId from the backend? What is the call/endpoint again?
4 Replies
kapa.ai
kapa.ai2w ago
Hi @WWWillems. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the knowledge sources, there are a couple of approaches to handle authentication in your custom API calls in Wasp. Using the Axios wrapper from wasp/client/api The recommended way to make authenticated API calls in Wasp is to use the built-in Axios wrapper that automatically handles authentication for you:
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}
This wrapper will automatically include the necessary authentication headers, so you don't need to manually extract the session ID from localStorage. This is the cleanest and most secure approach. Wasp Docs: Using the API from the Client Authentication in Wasp Wasp uses sessions for authentication, which are stored in localStorage on the client and in the database on the server. Under the hood, Wasp uses Lucia Auth v3 for session management. Wasp Docs: Auth Overview - Sessions If you need to check if a user is authenticated in your custom API implementation, you can use the context object that Wasp injects into your API handlers. This object contains user session information:
export const fooBar = (req, res, context) => {
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
export const fooBar = (req, res, context) => {
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
Wasp Docs: Defining the API's NodeJS Implementation Regarding the endpoint to fetch the session ID from the backend, Wasp has an /auth/me endpoint that returns session information, but it's not recommended to use this directly for authentication purposes in your API calls. Instead, use the provided api wrapper from wasp/client/api. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @WWWillems, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
WWWillems
WWWillemsOP2w ago
ahah, was looking for getSessionId() from wasp/client/api ! 👍
Vinny (@Wasp)
Vinny (@Wasp)2w ago
nice, did that work?
WWWillems
WWWillemsOP2w ago
Yes sir all good 👍

Did you find this page helpful?