Skip to content

Commit

Permalink
clients/web: avoid calling /users/me if the cookie is not set
Browse files Browse the repository at this point in the history
  • Loading branch information
frankie567 committed Nov 7, 2024
1 parent 721ce53 commit b23a58b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
17 changes: 5 additions & 12 deletions clients/apps/web/src/utils/api/serverside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions clients/apps/web/src/utils/user.ts
Original file line number Diff line number Diff line change
@@ -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<UserRead | undefined> => {
// 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' })
Expand Down

0 comments on commit b23a58b

Please sign in to comment.