Session Access and Management

Prior to v0.5.0 useAuth() was called useSession().

The useAuth composable is your main gateway to accessing and manipulating session-state and data. Here's the main methods you can use:

const {  status,  data,  lastRefreshedAt,  getCsrfToken,  getProviders,  getSession,  signIn,  signOut,} = useAuth()// Session status, either `unauthenticated`, `loading`, `authenticated`, see Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), `loading` (= session loading in progress), see Time at which the session was last refreshed, either `undefined` if no refresh was attempted or a `Date`-object of the time the refresh happenedlastRefreshedAt.value// Get / Reload the current session from the server, pass `{ required: true }` to force a login if no session exists, see getSession()// Get the current CSRF token, usually you do not need this function, see getCsrfToken()// Get the supported providers, e.g., to build your own login page, see getProviders()// Trigger a sign-in, see signIn()// Trigger a sign-in with a redirect afterwards, see signIn(undefined, { callbackUrl: '/protected' })// Trigger a sign-in via a specific authentication provider with a redirect afterwards, see signIn('github', { callbackUrl: '/protected' })// Trigger a sign-in with username and password already passed, e.g., from your own custom-made sign-in formawait signIn('credentials', { username: 'jsmith', password: 'hunter2' })// Trigger a sign-out, see signOut()// Trigger a sign-out and send the user to the sign-out page afterwardsawait signOut({ callbackUrl: '/signout' })

Session data.value has the following interface:

interface DefaultSession {  user?: {    name?: string | null;    email?: string | null;    image?: string | null;  };  expires: ISODateString;}

Note that this is only set when the use is logged-in and when the provider used to login the user provides the fields.


You can also pass the callbackUrl option to both the signIn, the signOut and the getSession method. This allows you to redirect a user to a certain pages, after they've completed the action. This can be useful when a user attempts to open a page (/protected) but has to go through external authentication (e.g., via their google account) first.

You can use it like:

await signIn({ callbackUrl: '/protected' })

to redirect the user to the protected page they wanted to access after they've been authenticated.

You can do the same for signing out the user:

await signOut({ callbackUrl: '/protected' })

E.g., to redirect the user away from the already loaded, protected, page after signout (else, you will have to handle the redirect yourself).

You may also pass specify a callback for the getSession utility:

await getSession({ callbackUrl: '/protected' })