diff --git a/docs/content/v0.6/3.application-side/2.session-access-and-management.md b/docs/content/v0.6/3.application-side/2.session-access-and-management.md index 8a7a7183..302bfa1c 100644 --- a/docs/content/v0.6/3.application-side/2.session-access-and-management.md +++ b/docs/content/v0.6/3.application-side/2.session-access-and-management.md @@ -1,5 +1,7 @@ # 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: ::code-group ```ts [authjs] @@ -132,6 +134,18 @@ This is a configuration option available to dynamically type the `SessionData` t `nuxt-auth` uses [unjs/knitwork](https://github.com/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: + +::code-group +```ts [local] +// force update the current session +await getSession({ force: true }) +``` +:: + ## 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. diff --git a/src/runtime/composables/local/useAuth.ts b/src/runtime/composables/local/useAuth.ts index 2054f8c6..8c9fb366 100644 --- a/src/runtime/composables/local/useAuth.ts +++ b/src/runtime/composables/local/useAuth.ts @@ -72,11 +72,11 @@ const getSession: GetSessionFunc = async (getSessionO const { path, method } = config.endpoints.getSession const { data, loading, lastRefreshedAt, token, rawToken } = useAuthState() - if (!token.value) { + if (!token.value && !getSessionOptions?.force) { return } - const headers = new Headers({ [config.token.headerName]: token.value } as HeadersInit) + const headers = new Headers(token.value ? { [config.token.headerName]: token.value } as HeadersInit : undefined) loading.value = true try { diff --git a/src/runtime/types.ts b/src/runtime/types.ts index 3770e881..b4e6e1eb 100644 --- a/src/runtime/types.ts +++ b/src/runtime/types.ts @@ -339,6 +339,11 @@ export type GetSessionOptions = Partial<{ required?: boolean callbackUrl?: string onUnauthenticated?: () => void + /** Whether to refetch the session even if the token returned by useAuthState is null. + * + * @default false + */ + force?: boolean }> // TODO: These types could be nicer and more general, or located withing `useAuth` files and more specific