Session Access and Management

useAuth Composable

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

authjs
const {  status,  data,  lastRefreshedAt,  getCsrfToken,  getProviders,  getSession,  signIn,  signOut,} = useAuth()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), `loading` (= session loading in progress), see https://next-auth.js.org/getting-started/client#signoutdata.value// 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 existsawait getSession()// Get the current CSRF token, usually you do not need this function, see https://next-auth.js.org/getting-started/client#signoutawait getCsrfToken()// Get the supported providers, e.g., to build your own login page, see https://next-auth.js.org/getting-started/client#getprovidersawait getProviders()// Trigger a sign-in, see https://next-auth.js.org/getting-started/client#signinawait signIn()// Trigger a sign-in with a redirect afterwards, see https://next-auth.js.org/getting-started/client#signinawait signIn(undefined, { callbackUrl: '/protected' })// Trigger a sign-in via a specific authentication provider with a redirect afterwards, see https://next-auth.js.org/getting-started/client#signinawait 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 https://next-auth.js.org/getting-started/client#signoutawait signOut()// Trigger a sign-out and send the user to the sign-out page afterwardsawait signOut({ callbackUrl: '/signout' })
local
const {  status,  data,  token,  lastRefreshedAt,  getSession,  signUp,  signIn,  signOut,} = useAuth()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returnsdata.value// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034`token.value// 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 existsawait getSession()// Trigger a sign-up, where `credentials` are the credentials your sign-up endpoint expects, e.g. `{ name:'Alice', email: '[email protected]', password: 'securepassword' }`await signUp(credentials);// Trigger a sign-up with auto sign-in and redirect to the profile page within the applicationawait signUp(credentials, { callbackUrl: '/profile', redirect: true });// Trigger a sign-up with auto sign-in and redirect to an external website (https://external.example.com)await signUp(credentials, { callbackUrl: 'https://external.example.com', redirect: true, external: true });// Trigger a sign-up without auto sign-in and redirect to the home page within the applicationawait signUp(credentials, { callbackUrl: '/', redirect: true }, { preventLoginFlow: true });// Trigger a sign-up without auto sign-in and doesn't redirect anywhereawait signUp(credentials, undefined, { preventLoginFlow: true });// Trigger a sign-in, where `credentials` are the credentials your sign-in endpoint expected, e.g. `{ username: 'bernd', password: 'hunter2' }`await signIn(credentials)// Trigger a sign-in with a redirect afterwardsawait signIn(credentials, { callbackUrl: '/protected' })// Trigger a sign-in with a redirect afterwards to an external page (if set, this will cause a hard refresh of the page)await signIn(credentials, { callbackUrl: 'https://sidebase.io', external: true })// Trigger a sign-outawait signOut()// Trigger a sign-out and send the user to the sign-out page afterwardsawait signOut({ callbackUrl: '/signout' })
refresh
const {  status,  data,  token,  lastRefreshedAt,  getSession,  signUp,  signIn,  signOut,  refresh,  refreshToken} = useAuth()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returnsdata.value// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034`token.value// The fetched refreshToken that can be used to token . E.g., a refreshToken like so: `eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034`refreshToken.value// 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 existsawait getSession()// Trigger a sign-in, where `credentials` are the credentials your sign-in endpoint expected, e.g. `{ username: 'bernd', password: 'hunter2' }`await signIn(credentials)// Trigger a sign-in with a redirect afterwardsawait signIn(credentials, { callbackUrl: '/protected' })// Trigger a sign-in with a redirect afterwards to an external page (if set, this will cause a hard refresh of the page)await signIn(credentials, { callbackUrl: 'https://sidebase.io', external: true })// Trigger a refresh, this will set token to new valueawait refresh()// Trigger a sign-outawait signOut()// Trigger a sign-out and send the user to the sign-out page afterwardsawait signOut({ callbackUrl: '/signout' })

SessionData

As described above you can use:

const { data } = useAuth()

to access the session-data of the currently logged in user. Depending on the provider you use, this data will be typed differently:

authjs
interface SessionData {  user?: {    name?: string | null;    email?: string | null;    image?: string | null;  };  expires: ISODateString;}
local
// Option A: No explicit configurationinferface SessionData {     id: string | number}// Option B: You configured `auth.provider.sessionDataType` to something like ` { id: 'string', email: 'string', name: 'string', role: 'admin | guest | account' }`inferface SessionData {   id: string  email: string  name: string  role: 'admin' | 'guest' | 'account'}

About auth.provider.sessionDataType

This is a configuration option available to dynamically type the SessionData that the local provider will return when accessing data.value. Read more about this in the nuxt.config.ts configuration documentation of the local provider.

nuxt-auth uses unjs/knitwork to generate the correct typescript interface from the type you provide.

Force refetching the session (local provider only)

Calling getSession will by default only refetch the current session if the token returned by useAuthState is defined. Passing the { force: true } option will always update the current session:

local
// force update the current sessionawait getSession({ force: true })

Automatic session refreshing

To activate or deactivate a periodical session refresh or session refresh when refocusing the window, please consult the nuxt.config.ts configuration documentation of the session object.

Redirects

You can also pass the callbackUrl option to both the signIn, the signOut and the getSession methods. 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:

authjs
await signIn(undefined, { callbackUrl: '/protected' })await signOut({ callbackUrl: '/protected' })await getSession({ callbackUrl: '/protected' })
local
const credentials = { username: 'bernd', password: 'hunter2' }await signIn(credentials, { callbackUrl: '/protected' })await signOut(credentials, { callbackUrl: '/protected' })await getSession(credentials, { callbackUrl: '/protected' })
refresh
const credentials = { username: 'bernd', password: 'hunter2' }await signIn(credentials, { callbackUrl: '/protected' })await signOut(credentials, { callbackUrl: '/protected' })await getSession(credentials, { callbackUrl: '/protected' })

useAuthState Composable

The useAuthState composable is the underlying storage layer to access the session-state and data. Here's the main methods and properties you can use:

authjs
const {  status,  loading,  data,  lastRefreshedAt} = useAuthState()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Whether any http request is still pendingloading.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), `loading` (= session loading in progress), see https://next-auth.js.org/getting-started/client#signoutdata.value// 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
local
const {  status,  loading,  data,  lastRefreshedAt,  token,  rawToken,  setToken,  clearToken} = useAuthState()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Whether any http request is still pendingloading.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returnsdata.value// 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// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034`token.value// Cookie that containes the raw fetched token string. This token won't contain any modification or prefixes like `Bearer` or any other.rawToken.value// Helper method to quickly set a new token (alias for rawToken.value = 'xxx')setToken('new token')// Helper method to quickly delete the token cookie (alias for rawToken.value = null)clearToken()
refresh
const {  status,  loading,  data,  lastRefreshedAt,  token,  rawToken,  setToken,  clearToken,  rawRefreshToken,  refreshToken} = useAuthState()// Session status, either `unauthenticated`, `loading`, `authenticated`status.value// Whether any http request is still pendingloading.value// Session data, either `undefined` (= authentication not attempted), `null` (= user unauthenticated), or session / user data your `getSession`-endpoint returnsdata.value// 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// The fetched token that can be used to authenticate future requests. E.g., a JWT-Bearer token like so: `Bearer eyDFSJKLDAJ0-3249PPRFK3P5234SDFL;AFKJlkjdsjd.dsjlajhasdji89034`token.value// The fetched refreshToken that can be used to refresh the Token with  refresh() methode. refreshToken.value// Cookie that containes the raw fetched token string. This token won't contain any modification or prefixes like `Bearer` or any other.rawToken.value// Cookie that containes the raw fetched refreshToken string.rawRefreshToken.value// Helper method to quickly set a new token (alias for rawToken.value = 'xxx')setToken('new token')// Helper method to quickly delete the token and refresh Token cookie (alias for rawToken.value = null and rawRefreshToken.value = null)clearToken()
Local provider: Note that you will have to manually call getSession from useAuth composable in order to refresh the new user state when using setToken, clearToken or manually updating rawToken.value:
const { getSession } = useAuth()const { setToken } = useAuthState()// ...setToken('...')await getSession()