serverAuth()
Use server-side auth utilities in @nuxtjs/better-auth.
- `serverAuth(event?)` — returns the Better Auth instance. Pass `event` in Nitro handlers for request-scoped database access and configuration context
- `getUserSession(event)` — get current session (auto-imported in `server/`)
- `requireUserSession(event, options?)` — throws 401 if not authenticated, supports role matching
- `getRequestSession(event)` — request-cached session, preferred over repeated `getUserSession` in same request
- `setRequestSession(event, session)` — supply an authenticated session to downstream helpers for the current request
- `refreshSessionCookieCache(event)` — refresh Better Auth's cached session cookie after server-side session data changes
- All server utils are auto-imported, no import statements needed
Use this page when you need authentication state or Better Auth APIs inside Nitro handlers, middleware, plugins, or other server-side code.
serverAuth(event?) returns the Better Auth instance. Pass event in Nitro handlers for request-scoped database access and ctx.requestOrigin. In production, the canonical auth URL comes from runtimeConfig.public.siteUrl or platform environment variables. Development can infer it from the request. Outside request contexts, such as seed scripts and tasks, call serverAuth() without an event.
When to Use What
| Task | Use | Example |
|---|---|---|
| Get request-cached session context | getRequestSession(event) | Cache once per request with context-backed storage when available |
| Supply a request session | setRequestSession(event, session) | Reuse a session resolved by trusted server authentication |
| Get current session | getUserSession(event) | Check if user is logged in |
| Refresh cached session cookie | refreshSessionCookieCache(event) | Use after updating data returned by Better Auth session helpers |
| Require authentication | requireUserSession(event) | Protect an API route |
| Access Better Auth API | serverAuth(event) | Call auth.api.listSessions() |
| Get session with options | requireUserSession(event, { user: { role: 'admin' } }) | Role-based protection |
refreshSessionCookieCache(event) refreshes the cached session cookie. It does not update the session or user record; perform that update first.
Server endpoint path
The module registers Better Auth at /api/auth. defineServerAuth accepts only this basePath and rejects other values when resolving the config. Remove a custom server basePath or set it to /api/auth; update client URLs and OAuth callback URLs accordingly.
External backends configured with auth.clientOnly: true can still use a custom basePath in defineClientAuth.