Skip to main content

Sessions

A Session represents the current authenticated entity using the application.

interface Session {
user: SessionUser
session: { id: string; token: string; expiresAt: Date; userId: string; /* ... */ }
entity: {
id: string
organization: { id: string; name: string }
permissions: Permission[]
}
}

All session functions are imported from @repo/auth/server.

getSession

Returns the current session or undefined. Throws a 401 error by default when no session exists.

import { getSession } from '@repo/auth/server'

const session = getSession()

// Suppress the error -- returns undefined instead
const session = getSession({ throwError: false })

Internally checks AsyncLocalStorage first (for queue jobs), then falls back to getRequestEvent().locals.session.

getUserSession

Same as getSession but guarantees the user and entity are present. Returns a UserSession type where user.id and entity.organization are non-nullable.

import { getUserSession } from '@repo/auth/server'

const session = getUserSession() // throws 401 if not a user session
session.user.id // string (never undefined)
session.entity.organization.id // string (never undefined)

isUserSession

Type guard to narrow Session | null to UserSession.

import { isUserSession } from '@repo/auth/server'

const session = getSession({ throwError: false })
if (isUserSession(session)) {
// session.user.id is guaranteed
}

useSystemSession

Temporarily overrides the session in locals with a system-level session that has wildcard (*) permissions. Restores the original session after the callback completes.

import { useSystemSession } from '@repo/auth/server'

await useSystemSession(organizationId, userId, async () => {
// Any call to getSession() here returns the system session
// Permissions: domain '*', actions ['*']
})

runWithSession

Runs a callback within an AsyncLocalStorage context so that getSession / getUserSession work outside of HTTP request handlers (e.g. queue jobs).

import { runWithSession } from '@repo/auth/server'

await runWithSession(session, async () => {
// getSession() returns the provided session here
})

If session is undefined, the callback runs without setting any context.