Skip to content

Commit 5fc1cfd

Browse files
authored
docs: improve getServerSession docs by showing how to pass along cookies during universal rendering (#124)
1 parent 0568254 commit 5fc1cfd

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

docs/content/4.server-side/2.session-access-and-route-protection.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ export default eventHandler(async (event) => {
1111

1212
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.
1313

14+
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:
15+
```ts
16+
const headers = useRequestHeaders(['cookie']) as HeadersInit
17+
const { data: token } = await useFetch('/api/token', { headers })
18+
```
19+
1420
## Endpoint Protection
1521

1622
To protect an endpoint, check the session after fetching it:

docs/content/4.server-side/3.jwt-access.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ Then from your application-side code you can fetch it like this:
3636
</template>
3737
3838
<script setup lang="ts">
39-
const headers = useRequestHeaders(['cookie'])
40-
const { data: token } = await useFetch('/api/token', { headers: { cookie: headers.cookie } })
39+
const headers = useRequestHeaders(['cookie']) as HeadersInit
40+
const { data: token } = await useFetch('/api/token', { headers })
4141
</script>
4242
```
4343

playground/app.vue

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ const { data, status, lastRefreshedAt, getCsrfToken, getProviders } = useSession
5555
const providers = await getProviders()
5656
const csrfToken = await getCsrfToken()
5757
58-
const headers = useRequestHeaders(['cookie'])
59-
const { data: token } = await useFetch('/api/token', { headers: { cookie: headers.cookie } })
58+
const headers = useRequestHeaders(['cookie']) as HeadersInit
59+
const { data: token } = await useFetch('/api/token', { headers })
6060
6161
const route = useRoute()
6262
</script>

0 commit comments

Comments
 (0)