Skip to content

Commit

Permalink
feat: add useAuthFetch for auto access token refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
becem-gharbi committed Jan 19, 2023
1 parent 39f6b28 commit 3c6ccda
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 19 deletions.
19 changes: 1 addition & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ A Nuxt 3 module to handle authentication
- Route middleware auth protection
- Database agnostic (Prisma based)
- Auth operations through `useAuth` composable
- Auto refresh of access token through `useAuthFetch` composable
- Typescript support

## Demo
Expand Down Expand Up @@ -154,24 +155,6 @@ definePageMeta({ middleware: "auth" }); // Redirects to login path when not logg
definePageMeta({ middleware: "guest" }); // Redirects to home path when loggedIn
```

<br>

For handling refresh of access token you can use `prefetch` method

```javascript
const { prefetch, useAccessToken } = useAuth();
const accessToken = useAccessToken();

const { data, error } = await useFetch("/api/protected", {
async onRequest({ request, options }) {
await prefetch();
if (accessToken) {
options.headers = { Authorization: "Bearer " + accessToken };
}
},
});
```

## Appendix

![workflow](https://github.com/becem-gharbi/nuxt-auth/blob/beta/workflow.png)
Expand Down
11 changes: 10 additions & 1 deletion playground/pages/home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,18 @@
</template>

<script setup lang="ts">
import { User } from '.prisma/client';
definePageMeta({ middleware: "auth" })
const { logout, fetchUser } = useAuth()
const { logout } = useAuth()
async function fetchUser() {
const data = await useAuthFetch<User>("/api/auth/me")
console.log(data)
}
async function handleLogout() {
await logout()
Expand Down
25 changes: 25 additions & 0 deletions src/runtime/composables/useAuthFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import useAuth from "./useAuth";
import { defu } from "defu";
import type { FetchOptions } from "ohmyfetch";

export default async function <DataT>(
path: string,
fetchOptions: FetchOptions = {}
): Promise<DataT> {
const { useAccessToken, prefetch } = useAuth();

const accessToken = useAccessToken();

await prefetch();

if (accessToken.value) {
fetchOptions.headers = defu(
{
Authorization: "Bearer " + accessToken.value,
},
fetchOptions.headers
);
}

return $fetch<DataT>(path, fetchOptions);
}

0 comments on commit 3c6ccda

Please sign in to comment.