#Concept clarification: where/how to persist bearer token?

5 messages · Page 1 of 1 (latest)

reef tusk
#

A broad question in the context of learning and experimenting with nextjs on a hobby app (using the old folder layout):
I have a single /API route that simply fetches another external api for content. This other external api requires a bearer token, and in my naive implementation I just got the token the via a manual POST and saved the string token as env variable, which is clearly not the solution since it expires every month and I need a way to automate this.

My first thought is to somehow create a middleware (overshoot for a single handler but I'm trying to exercise), that checks if the auth token is available / not expired and if not to refetches it and pass it to the next function which will effectively fetch for data. Here is where I'm missing it, where should such token be stored (because I guess requesting another auth for each page visit is not correct) ? Necessarily on an external service, like a db that needs to be queried? Because my uneducated guess is cookies are on the browser side, and the API that is run on the server does not have access to that? Wrong? And if so, is it safe to store such a token in the browser as a cookie?

stuck socketBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

lusty quiver
#

in general, you can have a token stored in a cookie, which can be retrieved from server side code as cookie is just a part of HTTP request headers.
Indeed Auth.js has a mechanism to store tokens safely in a cookie(JWT encrypted)
Usually OAuth providers such as Google returns an access token so you can bake it inside JWT, then retrive it from server side then invoke Google API along with the token.

#

oh. bear toke, api key or something should not be exposed to client sides such as cookie. keep it in server side like ENV or secret key services AWS/Google/Azure provide.

reef tusk
#

hmm, I was wondering, since the bearer authorizes my server to ask for data, passing that to the client would be also conceptually wrong. Maybe the fastest solution is Vercel KV, so storing that auth token to a database known only to the server? I never used that though