From b23a58bca0864bc64799685d5ab18bf3e5d734c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Voron?= Date: Thu, 7 Nov 2024 16:53:15 +0100 Subject: [PATCH] clients/web: avoid calling /users/me if the cookie is not set --- clients/apps/web/src/utils/api/serverside.ts | 17 +++++------------ clients/apps/web/src/utils/user.ts | 10 ++++++++++ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/clients/apps/web/src/utils/api/serverside.ts b/clients/apps/web/src/utils/api/serverside.ts index 9c29c7483e..a379fff50a 100644 --- a/clients/apps/web/src/utils/api/serverside.ts +++ b/clients/apps/web/src/utils/api/serverside.ts @@ -3,7 +3,7 @@ import { cookies, headers as getOriginalHeaders } from 'next/headers' import { cache } from 'react' import { getServerURL } from '.' -const _getServerSideAPI = (token?: string): PolarAPI => { +const _getServerSideAPI = (): PolarAPI => { let headers: HTTPHeaders = {} const originalHeaders = getOriginalHeaders() @@ -15,17 +15,10 @@ const _getServerSideAPI = (token?: string): PolarAPI => { } } - if (token) { - headers = { - ...headers, - Authorization: `Bearer ${token}`, - } - } else { - const cookieStore = cookies() - headers = { - ...headers, - Cookie: cookieStore.toString(), - } + const cookieStore = cookies() + headers = { + ...headers, + Cookie: cookieStore.toString(), } // When running inside GitHub Codespaces, we need to pass a token to access forwarded ports diff --git a/clients/apps/web/src/utils/user.ts b/clients/apps/web/src/utils/user.ts index 8aa1a14909..a75da47e19 100644 --- a/clients/apps/web/src/utils/user.ts +++ b/clients/apps/web/src/utils/user.ts @@ -1,9 +1,19 @@ import { Organization, PolarAPI, ResponseError, UserRead } from '@polar-sh/sdk' +import { cookies } from 'next/headers' import { cache } from 'react' +const POLAR_AUTH_COOKIE_KEY = + process.env.POLAR_AUTH_COOKIE_KEY || 'polar_session' + const _getAuthenticatedUser = async ( api: PolarAPI, ): Promise => { + // Optimization: if the cookie is not set, the user is not authenticated + const cookieStore = cookies() + if (!cookieStore.has(POLAR_AUTH_COOKIE_KEY)) { + return undefined + } + try { // Don't cache it on Next.js edge cache... return await api.users.getAuthenticated({ cache: 'no-cache' })