Next.js Discord

Discord Forum

Using HTTP only cookies (authentication tokens) in client components.

Unanswered
American Sable posted this in #help-forum
Open in Discord
Avatar
American SableOP
I am storing my access and refresh token as HTTP only cookies.
How do you guys get access to these tokens in the apis called from client components (react query), I want to use the access token as Bearer token.

16 Replies

Avatar
u pass the token down from a rsc
or u build a hook that will be populated when layout mounts
with the token
Avatar
Saltwater Crocodile
Are you using any authentication library
Avatar
American SableOP
No, using a laravel api.
Passing the token down to RSC is a good approach but I want to make the token access centrally on a Authorization headers.
Avatar
Saltwater Crocodile
well, you can also create a function that uses the token with react query and the use that for your auth queries
Avatar
American SableOP
I was using server actions to get Http only cookies and it works but that might not be a good approach. It is calling middleware everytime even though sending request from react query.
Avatar
Saltwater Crocodile
Better still you can use a hook
Avatar
American SableOP
But how do I populate my hook, by passing tokens from layout and store it in a global context?
But I had read to not store HTTP only cookies in redux or context etc
Avatar
Saltwater Crocodile
Okay, so after logging in you can just store your tokens somewhere globally right
Also you can access cookies in your client components as well
Avatar
American SableOP
Not HTTP only cookies
Avatar
Just do what gin said. Get the cookie from the server component and pass it to the client component via prop.

By the way the whole point of http only cookie is to not make it available to client side JavaScript so what you are doing just… defeats the whole purpose? Why did you make it a http only cookie in the first place