Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ export default eventHandler(async (event) => {

This is inspired by [the `getServerSession`](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes) of NextAuth.js. It also avoids an external, internet call to the `GET /api/auth/sessions` endpoint, instead directly calling a pure JS-method.

Note: If you use [Nuxts' `useFetch`](https://nuxt.com/docs/api/composables/use-fetch) from your app-components to fetch data from an endpoint that uses `getServerSession` or [`getToken`](/nuxt-auth/server-side/jwt-access) you will need to manually pass along cookies as [Nuxt 3 universal rendering](https://nuxt.com/docs/guide/concepts/rendering#universal-rendering) will not do this per-default when it runs on the server-side. Not passing along cookies will result in `getServerSession` returning `null` when it is called from the server-side as no auth-cookies will exist. Here's an example that manually passes along cookies:
```ts
const headers = useRequestHeaders(['cookie']) as HeadersInit
const { data: token } = await useFetch('/api/token', { headers })
```

## Endpoint Protection

To protect an endpoint, check the session after fetching it:
Expand Down
4 changes: 2 additions & 2 deletions docs/content/4.server-side/3.jwt-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ Then from your application-side code you can fetch it like this:
</template>

<script setup lang="ts">
const headers = useRequestHeaders(['cookie'])
const { data: token } = await useFetch('/api/token', { headers: { cookie: headers.cookie } })
const headers = useRequestHeaders(['cookie']) as HeadersInit
const { data: token } = await useFetch('/api/token', { headers })
</script>
```

Expand Down
4 changes: 2 additions & 2 deletions playground/app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ const { data, status, lastRefreshedAt, getCsrfToken, getProviders } = useSession
const providers = await getProviders()
const csrfToken = await getCsrfToken()

const headers = useRequestHeaders(['cookie'])
const { data: token } = await useFetch('/api/token', { headers: { cookie: headers.cookie } })
const headers = useRequestHeaders(['cookie']) as HeadersInit
const { data: token } = await useFetch('/api/token', { headers })

const route = useRoute()
</script>