From 0842ed62bea992f7fabc4bb43b5ca66ccc42f8e2 Mon Sep 17 00:00:00 2001 From: BracketJohn Date: Fri, 23 Dec 2022 17:47:43 +0100 Subject: [PATCH] docs: improve getServerSession docs by showing how to pass along cookies during universal rendering --- .../4.server-side/2.session-access-and-route-protection.md | 6 ++++++ docs/content/4.server-side/3.jwt-access.md | 4 ++-- playground/app.vue | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/content/4.server-side/2.session-access-and-route-protection.md b/docs/content/4.server-side/2.session-access-and-route-protection.md index 704abfcb..8697d6b4 100644 --- a/docs/content/4.server-side/2.session-access-and-route-protection.md +++ b/docs/content/4.server-side/2.session-access-and-route-protection.md @@ -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: diff --git a/docs/content/4.server-side/3.jwt-access.md b/docs/content/4.server-side/3.jwt-access.md index 6a29e4d5..bcbe6653 100644 --- a/docs/content/4.server-side/3.jwt-access.md +++ b/docs/content/4.server-side/3.jwt-access.md @@ -36,8 +36,8 @@ Then from your application-side code you can fetch it like this: ``` diff --git a/playground/app.vue b/playground/app.vue index 3e94a727..77e2aa32 100644 --- a/playground/app.vue +++ b/playground/app.vue @@ -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()