S
SolidJS6mo ago
hannus

is it necessary to mark "use server" for useSession

"use server" means executing only on the server. So, is it necessary to mark "use server" for useSession of h3? If marked, is there a risk of execution order issues? In the example (with-auth), I did not see the "use server" marker. However, in one of my experimental projects, if I don’t add "use server", the build fails. After adding "use server" and successfully building, every time I refresh the page, the previously initialized h3 session with data gets cleared. I suspect that use server is causing a delay in the execution time of useSession. Here is the code where I use useSession:
export async function getSession(): Promise<ReturnType<typeof useSession>> {
"use server";
return useSession({
password: process.env.SESSION_SECRET ?? "secretsecretsecretsecretsecretsecretsecretsecretsecretsecret",
});
}
export async function getSession(): Promise<ReturnType<typeof useSession>> {
"use server";
return useSession({
password: process.env.SESSION_SECRET ?? "secretsecretsecretsecretsecretsecretsecretsecretsecretsecret",
});
}
thanks a lot
4 Replies
Madaxen86
Madaxen866mo ago
Well, just like in the with-auth example https://github.com/solidjs/solid-start/blob/main/examples/with-auth/src/lib/index.ts you only call useSession/getSession in functions with “use server“ then you won’t need it. But if you accidentally call it from a function which is exposed to the client you will leak your secret encryption key to the client. Regarding the recreation of the session every time useSession is called: without more context of what you actually do, nobody can help you. Maybe you can provide a stackblitz with the essential parts of your code?
GitHub
solid-start/examples/with-auth/src/lib/index.ts at main · solidjs/s...
SolidStart, the Solid app framework. Contribute to solidjs/solid-start development by creating an account on GitHub.
hannus
hannusOP6mo ago
thanks, in the dev mode, everything goes well. However, Recreation of session occurs in prod mode. Thus, I think there would be sth wrong with build process. I am going to check the code with a new tiny project, and provide a stackblitz later. Actually, I have not used it ever. Solidstart project is the my first js project in this century;) Modern js tools is too new to me. my code as following:
export async function getSession(): Promise<ReturnType<typeof useSession>> {
"use server";
console.log("useSession", useSession);
return useSession({
password: process.env.SESSION_SECRET ?? "secret",
});
}

export async function getTokenFromSession(): Promise<Token | undefined> {
"use server";
const session = await getSession();
const sessionData = session.data as SessionData;

const token = sessionData?.token;
return token;
}

export async function fetchUserInfo(
getToken: () => Promise<Token | undefined>,
api: string
): Promise<UserPublicWeb | undefined> {
"use server";

try {
const token = await getToken();
console.log("token", token);
if (token === undefined) {
return undefined;
}

const response = await fetch(api, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});

if (!response.ok) {
throw new Error(
`HTTP error! status: ${response.status}; detail: ${response.statusText}`
);
}

const user = (await response.json()) as UserPublicWeb;
console.log("user", user);
return user;
} catch (error) {
console.error("Failed to fetch user info:", error);
return undefined;
}
}

// cache the user info
export const userInfoCache = cache(fetchUserInfo, "userInfo");
export async function getSession(): Promise<ReturnType<typeof useSession>> {
"use server";
console.log("useSession", useSession);
return useSession({
password: process.env.SESSION_SECRET ?? "secret",
});
}

export async function getTokenFromSession(): Promise<Token | undefined> {
"use server";
const session = await getSession();
const sessionData = session.data as SessionData;

const token = sessionData?.token;
return token;
}

export async function fetchUserInfo(
getToken: () => Promise<Token | undefined>,
api: string
): Promise<UserPublicWeb | undefined> {
"use server";

try {
const token = await getToken();
console.log("token", token);
if (token === undefined) {
return undefined;
}

const response = await fetch(api, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});

if (!response.ok) {
throw new Error(
`HTTP error! status: ${response.status}; detail: ${response.statusText}`
);
}

const user = (await response.json()) as UserPublicWeb;
console.log("user", user);
return user;
} catch (error) {
console.error("Failed to fetch user info:", error);
return undefined;
}
}

// cache the user info
export const userInfoCache = cache(fetchUserInfo, "userInfo");
Madaxen86
Madaxen866mo ago
try {
const token = await getToken(); // this should probably be getTokenFromSession() right?

try {
const token = await getToken(); // this should probably be getTokenFromSession() right?

Please notice that in the with-auth example useSession is imported from vinxi/http which wraps h3 in a function to make it work with vinxi.
hannus
hannusOP6mo ago
thanks. const token = await getToken(); getTOken() is a dependency injection of fetchUserInfo function. When I call this function, looks like following: userInfoCache(getTokenFromSession, "http://localhost:8000/getuserinfo/"); yep, I have imported useSession from 'vinxi/http'. in the dev mode it is okay, however, prod mode cannot work as expectation since the recreation of session in every refresh time. I have check the code of with-auth example, the only difference between my tiny project and example is whether add "use server" in the get_session() function. I am going to check it again in few hours. thanks again. My mistake. After building with Vinxi, the default value of secure for sessions is true, meaning it can only be set over HTTPS. During testing, I was not using HTTPS. Once I manually set secure to false in the session, the issue was resolved. This is certainly not a bug, but an oversight on my part. Sorry about that.
Want results from more Discord servers?
Add your server