#How to get Auth.js session in a `server$` function?

2 messages · Page 1 of 1 (latest)

sweet elm
#

I spent a good while on this today and haven't figured it out. I have a hobby app where I need to call Spotify Web API and so I need the user ID and my access token, which are stored in the session.

  • I tried using useSession hook but the linter says that's not possible in a server$ function
  • I tried using requestEvent.resolveValue but the Request Event doesn't seem to be exposed (right?)
  • I tried grabbing the session token from authjs.session-token cookie but that's encrypted and I haven't found any way to decrypt it manually
late vapor
#

It is supposed to be populated inside the sharedMap. Note that you have to access it with this.sharedMap so you can't use arrow functions and must use anonymous functions (see example below).

But to make things easier on our side we added these extra functions to be used inside server$ functions:

import { server$ } from "@builder.io/qwik-city";
import { AuthenticationError } from "~/lib/errors/authentication-error";
import type { Session, User } from "@auth/qwik";

interface AuthenticatedUser extends User {
  id: string;
  roles: string[];
  permissions: string[];
}

export const getCurrentUser = server$(function (): AuthenticatedUser {
  const session = this.sharedMap.get("session") as Session | null;
  if (!session?.user?.id) throw new AuthenticationError();

  const user = session.user;

  if (!user.roles) user.roles = [];
  if (!user.permissions) user.permissions = [];

  return user as AuthenticatedUser;
});

export const isAuthenticated = server$(function (): boolean {
  return !!this.sharedMap.get("session")?.user?.id;
});