In order to retrieve a session value, the useSession
function must be utilized.
import { useSession } from "vinxi/http";
export async function getUser(): Promise<User | null> {
const session = await useSession({
password: process.env.SESSION_SECRET
});
const userId = session.data.userId;
if (!userId) return null;
return await store.getUser(userId);
}
To set a session value, you should invoke the session.update
method. This is an asynchronous function:
await session.update((d: UserSession) => (d.userId = user!.id));
This is how it is implemented with server functions:
export async function login(formData: FormData) {
const username = String(formData.get("username"));
const password = String(formData.get("password"));
// perform validation
try {
const session = await getSession();
const user = await db.user.findUnique({ where: { username } });
if (!user || password !== user.password) return new Error("Invalid login");
await session.update((d: UserSession) => (d.userId = user!.id));
} catch (err) {
return err as Error;
}
throw redirect("/");
}
export async function logout() {
const session = await getSession();
await session.update((d: UserSession) => (d.userId = undefined));
throw redirect("/login");
}