Skip to content

feat: add setSessionCookie(event, token) server utility #296

@onmax

Description

@onmax

Problem

Custom auth flows (wallet signing, QR cross-device login, custom magic links) need to set a better-auth session cookie on an H3 event after creating a session programmatically. Currently the only way is reaching into internal APIs:

const auth = serverAuth(event)
const ctx = await auth.$context
const cookies = ctx.authCookies as Record<string, { name: string, attributes: {...} } | undefined>
const c = cookies.sessionToken!
setCookie(event, c.name, token, {
  httpOnly: c.attributes.httpOnly ?? true,
  secure: c.attributes.secure ?? true,
  sameSite: (c.attributes.sameSite?.toLowerCase() as 'lax' | 'strict' | 'none') ?? 'lax',
  path: c.attributes.path ?? '/',
  maxAge: c.attributes.maxAge,
})

This is fragile (depends on authCookies internal shape), verbose (10 lines for every call site), and undocumented.

Related upstream: better-auth/better-auth#7222

Proposed Solution

Auto-imported server utility:

// server/api/my-custom-auth.post.ts
const session = await createSessionForUser(event, userId)
await setSessionCookie(event, session.token)

The module already auto-imports serverAuth, requireUserSession, getUserSession. Adding setSessionCookie follows the same pattern and would unlock custom auth flows without internal API coupling.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions