#Access token from session in authentication header

1 messages · Page 1 of 1 (latest)

warm orbit
#

Hi, is it possible to somehow get the access token that I have stored in the session? I need it to send to server in api client.
E.g

function api(url: string) {
    const accessToken = '??'
    return fetch(...., {
        headers: {
            'Authorization': `Bearer ${accessToken}`
        }
    })
}
chilly cosmos
#

Get the session with sessionStorage.getSession passing the cookie header value, then do session.get(“token”)

warm orbit
#

Thank you., but I have a problem that I don't have a Request in the api method and therefore I can't get to the session. I have hundreds of those API methods, I can't send it manually every request. Look:


// companies.tsx
export const loader: LoaderFunction = async () => {
  const companies = await getCompanies()
  return json<LoaderData>({companies})
}

// companies.api.ts
async function getCompanies() {
  return api('/companies', 'GET')
}

// api.ts
function api(url: string, method: 'GET' | 'POST', 'PUT') {
    const accessToken = '??'
    return fetch(...., {
        headers: {
            'Authorization': `Bearer ${accessToken}`
        }
    })
}
chilly cosmos
#

Get the token in the loader and pass the token as argument to your api function

warm orbit
#

I probably have to do that in every loader. Or I can send the entire request to the api and get the access token from the session there. Good?

chilly cosmos
#

You can pass the request as a parameter too yes

#

I usually keep http related code in the loader

#

So my other functions are not attached to that