Skip to content

Commit

Permalink
feat: getSession force refetch option (#425)
Browse files Browse the repository at this point in the history
Co-authored-by: Nils <[email protected]>
Co-authored-by: Zoey <[email protected]>
  • Loading branch information
3 people authored Sep 23, 2023
1 parent 57c1431 commit e2ea743
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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]
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/composables/local/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ const getSession: GetSessionFunc<SessionData | null | void> = 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 {
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e2ea743

Please sign in to comment.